json字符串与java 类型的相互转换

  • Post author:
  • Post category:java


//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;

}



版权声明:本文为weixin_42201224原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。