jackson 问题定位

问题背景:

云计算Pass平台版本升级,导致引用的jackson的包直接由1.*升级为2.* 。在版本1.*中对于字段名与实际json不符的直接忽略了,而在2.*中则会报错。诸如此类,有较大差异,需要一一排查


一、配置maven依赖

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.5</version>
    </dependency> 

https://mvnrepository.com

二、测试类

 1 package com.example.myspring.transfer;
 2 
 3 import com.example.myspring.App;
 4 import com.fasterxml.jackson.core.JsonProcessingException;
 5 import com.fasterxml.jackson.databind.ObjectMapper;
 6 import org.junit.Test;
 7 
 8 import java.io.IOException;
 9 import java.util.Arrays;
10 import java.util.HashMap;
11 import java.util.Map;
12 
13 public class JacksonTest {
14 
15     private ObjectMapper objectMapper = new ObjectMapper();
16 
17     Map map = new HashMap();
18 
19     @Test
20     public void toJsonTest1() throws JsonProcessingException {
21         // 多种类型可以先封装为Map
22         map.put("alibaba", new App());
23         map.put("tengxun", Arrays.asList("weixin", "wangzherongyao"));
24         map.put("hugh", null);
25         map.put("DOU", "DOU");
26         System.out.println(objectMapper.writeValueAsString(map));
27         // {"alibaba":{},"DOU":"DOU","tengxun":["weixin","wangzherongyao"],"hugh":null}
28     }
29 
30     @Test
31     public void toJsonTest2() throws IOException {
32         // 新加非类Stu属性six,且值为null,依然可以被识别
33         String likeStu = "{"sto":"001","name":"xx", "six":null}";
34         Map<String, Object> mock = objectMapper.readValue(likeStu, Map.class); // {"sto":"001","name":"xx","six":null}
35         System.out.println(objectMapper.writeValueAsString(mock));
36     }
37 
38     public static class Stu{
39 
40         private String sto;
41         private String name;
42 
43         public Stu(String sto, String name) {
44             this.sto = sto;
45             this.name = name;
46         }
47 
48         public String getSto() {
49             return sto;
50         }
51 
52         public void setSto(String sto) {
53             this.sto = sto;
54         }
55 
56         public String getName() {
57             return name;
58         }
59 
60         public void setName(String name) {
61             this.name = name;
62         }
63     }
64 }

测试结果:

(1)未能复现项目中报错,推断与版本号有关联

(2)2.9.5  版本可以解析出以上结果;但是切换到 2.7.0 或者 以下版本,又报不同的错

三、总结

不同版本的jackson存在较大差异,坑较多

【参考】https://www.jianshu.com/p/4bd355715419

原文地址:https://www.cnblogs.com/Hughzm/p/9399068.html