项目在交互过程中,一般会使用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 对象时,需要按照自己的项目来获取此对象.