1. 程式人生 > >獲取request請求中post提交的JSON格式資料 並轉化成bean

獲取request請求中post提交的JSON格式資料 並轉化成bean

專案在互動過程中,一般會使用json格式進行資料的傳輸 . 需要把一些實體bean轉換成json格式, 有需要把json格式轉化成bean. 下面就是一個工具類,使用者 json串和java bean之間相互轉換

import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;

public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static <T> T convertJsonToBean(String json,Class<T> cls){
        try {
            return objectMapper.readValue(json,cls);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> String convertBeanToJson(T t){
        try {
            return objectMapper.writeValueAsString(t);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

接下來是接收請求類,把post請求資料中的Json格式的資料串獲取,並且轉換成Java Bean;

     //獲取post請求中 Json格式的資料
        BufferedReader streamReader = new BufferedReader( new InputStreamReader(this.request.getInputStream(), "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            responseStrBuilder.append(inputStr);
        }
        String jsonData = responseStrBuilder.toString();
        //轉換成bean
        RequestDTO request = JsonUtil.convertJsonToBean(jsonData.toString(), RequestDTO.class);

當然上面 獲取request 物件時,需要按照自己的專案來獲取此物件.