编写ObjectMapper工具类
public class ObjectMapperUtil {
private static final ObjectMapper MAPPER = new ObjectMapper();
//对象转JSON
public static String toJson(Object obj) {
try {
String json = MAPPER.writeValueAsString(obj);
return json;
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
}
}
//json转对象 ItemDesc itemDesc = (ItemDesc)ObjectMapperUtil.toObject(json,ItemDesc.class);
public static <T>T toObject(String json,Class<T> tartgetClass){
try {
return MAPPER.readValue(json, tartgetClass);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}