Json 工具类

一、使用方法

(1/4)普通对象转Json

  1. DodoFile file = new DodoFile();
  2. file.setFileName("test.file");
  3. // 普通对象转Json
  4. String s = JacksonUtil.toJackson(file);
  5. System.err.println(s);

(2/4)Json转普通对象

  1. DodoFile file = new DodoFile();
  2. file.setFileName("test.file");
  3. String s = JacksonUtil.toJackson(file);
  4. System.err.println(s);
  5. // Json转普通对象
  6. DodoFile file2 = JacksonUtil.toObject(s, DodoFile.class);
  7. System.err.println(file2);

(3/4)集合对象转Json

  1. Map<String, DodoFile> files = new HashMap<String, DodoFile>();
  2. DodoFile file = new DodoFile();
  3. file.setFileName("test.file");
  4. files.put("key1", file);
  5. // 集合对象转Json
  6. String s = JacksonUtil.toJackson(files);
  7. System.err.println(s);

(4/4)Json转集合对象

  1. Map<String, DodoFile> files = new HashMap<String, DodoFile>();
  2. DodoFile file = new DodoFile();
  3. file.setFileName("test.file");
  4. files.put("key1", file);
  5. String s = JacksonUtil.toJackson(files);
  6. System.err.println(s);
  7. // Json转集合对象,方式1
  8. Map<String, DodoFile> files2 = JacksonUtil.toObject(s, new TypeReference<Map<String, DodoFile>>() {});
  9. System.err.println(files2);
  10. // Json转集合对象,方式2
  11. Map<String, DodoFile> files3 = JacksonUtil.toCollectionObject(s, Map.class, String.class, DodoFile.class);
  12. System.err.println(files3);

二、注释说明

  1. public class JacksonUtil {
  2. private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
  3. // Java对象转Json
  4. public static String toJackson(Object object) throws JsonProcessingException {
  5. return object == null ? null : OBJECT_MAPPER.writeValueAsString(object);
  6. }
  7. // Json转Java对象
  8. public static <T> T toObject(String jsonStr, Class<T> clazz) throws IOException {
  9. if (StringUtils.isBlank(jsonStr)) {
  10. return null;
  11. }
  12. return OBJECT_MAPPER.readValue(jsonStr, clazz);
  13. }
  14. // Json转Java对象,类型安全
  15. public static <T> T toObject(String jsonStr, TypeReference<?> typeReference) throws IOException,
  16. JsonParseException, JsonMappingException {
  17. if (StringUtils.isBlank(jsonStr)) {
  18. return null;
  19. }
  20. return OBJECT_MAPPER.readValue(jsonStr, typeReference);
  21. }
  22. // Json转Java集合对象,类型安全,可使用toObject(String jsonStr, TypeReference<?> typeReference) 替代
  23. public static <T> T toCollectionObject(String jsonStr, Class<?> collectionClass, Class<?>... elementClasses)
  24. throws IOException, JsonParseException, JsonMappingException {
  25. if (StringUtils.isBlank(jsonStr)) {
  26. return null;
  27. }
  28. return OBJECT_MAPPER.readValue(jsonStr, getCollectionType(collectionClass, elementClasses));
  29. }
  30. private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
  31. return OBJECT_MAPPER.getTypeFactory().constructParametricType(collectionClass, elementClasses);
  32. }
  33. }