Json 处理技巧

  • 将对象转为 JSON 字符串
ObjectMapper objectMapper = new ObjectMapper();
String str = objectMapper.writeValueAsString(javaObj);
  • 将 JSON 字符串转为 Map
JavaType valueType = objectMapper.getTypeFactory()
.constructParametricType(HashMap.class, String.class, Object.class);
HashMap<String, Object> map = objectMapper.readValue(str, valueType);
  • 将 JSON 字符串转为 List
JavaType valueType = objectMapper.getTypeFactory()
.constructParametricType(ArrayList.class, Person.class);
List<Person> list = objectMapper.readValue(str, valueType);