Blame view

yudao-admin-server/src/main/java/cn/iocoder/dashboard/util/json/JsonUtils.java 2.25 KB
533cd1d3   YunaiV   再次调整项目结构
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
  package cn.iocoder.dashboard.util.json;
  
  import cn.hutool.core.util.ArrayUtil;
  import cn.hutool.core.util.StrUtil;
  import com.fasterxml.jackson.core.JsonProcessingException;
  import com.fasterxml.jackson.core.type.TypeReference;
  import com.fasterxml.jackson.databind.ObjectMapper;
  
  import java.io.IOException;
  import java.util.ArrayList;
  import java.util.List;
  
  /**
   * JSON 工具类
   *
   * @author 芋道源码
   */
  public class JsonUtils {
  
      private static ObjectMapper objectMapper = new ObjectMapper();
  
      /**
       * 初始化 objectMapper 属性
       * <p>
       * 通过这样的方式,使用 Spring 创建的 ObjectMapper Bean
       *
       * @param objectMapper ObjectMapper 对象
       */
      public static void init(ObjectMapper objectMapper) {
          JsonUtils.objectMapper = objectMapper;
      }
  
      public static String toJsonString(Object object) {
          try {
              return objectMapper.writeValueAsString(object);
          } catch (JsonProcessingException e) {
              throw new RuntimeException(e);
          }
      }
  
      public static <T> T parseObject(String text, Class<T> clazz) {
          if (StrUtil.isEmpty(text)) {
              return null;
          }
          try {
              return objectMapper.readValue(text, clazz);
          } catch (IOException e) {
              throw new RuntimeException(e);
          }
      }
  
      public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
          if (ArrayUtil.isEmpty(bytes)) {
              return null;
          }
          try {
              return objectMapper.readValue(bytes, clazz);
          } catch (IOException e) {
              throw new RuntimeException(e);
          }
      }
  
      public static <T> T parseObject(String text, TypeReference<T> typeReference) {
          try {
              return objectMapper.readValue(text, typeReference);
          } catch (IOException e) {
              throw new RuntimeException(e);
          }
      }
  
      public static <T> List<T> parseArray(String text, Class<T> clazz) {
          if (StrUtil.isEmpty(text)) {
              return new ArrayList<>();
          }
          try {
              return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
          } catch (IOException e) {
              throw new RuntimeException(e);
          }
      }
  
  }