Jackson 序列化工具类

基于 Jackson ObjectMapper 封装的 JSON 工具类,提供对象序列化与反序列化(含 List 泛型),并集中配置了常用序列化行为:

 1public class JSON {
 2    private final static ObjectMapper mapper = new ObjectMapper();
 3
 4    static {
 5
 6        // 美化输出
 7        //  mapper.enable(SerializationFeature.INDENT_OUTPUT);
 8        // 允许序列化空的POJO类
 9        // (否则会抛出异常)
10        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
11        // 把java.util.Date, Calendar输出为数字(时间戳)
12        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
13        // 在遇到未知属性的时候不抛出异常
14        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
15        // 强制JSON 空字符串("")转换为null对象值:
16        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
17        // 在JSON中允许C/C++ 样式的注释(非标准,默认禁用)
18        mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
19        // 允许没有引号的字段名(非标准)
20        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
21        // 允许单引号(非标准)
22        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
23        // 强制转义非ASCII字符
24        mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
25        // 所有的日期格式都统一为以下的样式,即yyyy-MM-dd HH:mm:ss
26        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
27
28        // 将内容包裹为一个JSON属性,属性名由@JsonRootName注解指定
29        // mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
30        mapper.registerModule(new JavaTimeModule());
31
32    }
33
34    public static void main(String[] args) {
35
36        List<Test> tests = new ArrayList<>();
37
38        Test test = new Test();
39
40        test.setId(1);
41        test.setTest("test");
42        test.setTid(10L);
43
44        test.setDate(new Date());
45        test.setDateTime(LocalDateTime.now());
46        tests.add(test);
47        String s = toJSONString(test);
48
49        System.out.println(s);
50        Test list = parseObject(s, Test.class);
51
52        System.out.println(list.toString());
53    }
54
55    public static <T> T parseObject(String text, Class<T> clazz) {
56        if (text != null) {
57            try {
58                return mapper.readValue(text, clazz);
59            } catch (IOException e) {
60                e.printStackTrace();
61            }
62        }
63        return null;
64    }
65
66    public static <T> T parseObject(String text, TypeReference<T> typeReference) {
67        if (text != null) {
68            try {
69                return mapper.readValue(text, typeReference);
70            } catch (IOException e) {
71                e.printStackTrace();
72            }
73        }
74        return null;
75    }
76
77    public static <T> List<T> parseArray(String text, Class<T> clazz) {
78        if (text != null) {
79            try {
80                JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, clazz);
81                return mapper.readValue(text, javaType);
82            } catch (IOException e) {
83                e.printStackTrace();
84            }
85        }
86        return null;
87    }
88
89    public static String toJSONString(Object clazz) {
90        if (clazz != null) {
91            try {
92                return mapper.writeValueAsString(clazz);
93            } catch (JsonProcessingException e) {
94                e.printStackTrace();
95            }
96        }
97        return "";
98    }
99}

配置说明:

  • FAIL_ON_EMPTY_BEANS / FAIL_ON_UNKNOWN_PROPERTIES 关闭后,序列化空对象、反序列化遇到多余字段都不再抛异常,接口更健壮。
  • 注册 JavaTimeModule 并统一日期格式为 yyyy-MM-dd HH:mm:ssLocalDateTime 也能正常序列化。
  • parseArray 通过 constructParametricType 构造 List<T> 类型,解决泛型擦除问题。