//java对象转json字符串
public static String toJsonStr(Object obj) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
//json字符串转java对象
public static <T> T toJavaObj(String json ,Class<T> clazz) {
ObjectMapper mapper = new ObjectMapper();
T t = null;
try {
t = mapper.readValue(json, clazz);
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
//将json字符串转为list集合
public static <T> List<T> toJavaObjList(String json ,Class<T> clazz) {
ObjectMapper mapper = new ObjectMapper();
try {
//忽略不认识的属性而不报错
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//确定集合的泛型类型
JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, clazz);
List<T> result = mapper.readValue(json, javaType);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}