解決json串和實體類字段不一致的問題

這裡我們對json串和實體類字段不一致的情況進行一個測試:

首先,我們建立一個實體類:這裡簡單定義瞭name,sex,age三個屬性,以及get set tostring方法。

public class Student {
 private String name;
 private String sex;
 private Integer age;
 public String getName() {
 return name;
 }
 public String getSex() {
 return sex;
 }
 public Integer getAge() {
 return age;
 }
 public void setName(String name) {
 this.name = name;
 }
 public void setSex(String sex) {
 this.sex = sex;
 }
 public void setAge(Integer age) {
 this.age = age;
 }
 @Override
 public String toString() {
 return "Student [name=" + name + ", sex=" + sex + ", age=" + age + "]";
 }
}

首先用fastjson進行測試:

當字段少於實體類字段:正常通過,沒有的字段會被賦予默認值

//fastjson 少字段
 @Test
 public void testFastjson01() {
 String jsonStr = "{\"age\":18,\"name\":\"zhangsan\"}";
 Student stu = JSON.parseObject(jsonStr, Student.class);
 System.out.println(stu); // Student [name=zhangsan, sex=null, age=18]
 }

當字段多於實體類字段:正常通過,沒有的字段不會被反序列化到對象中

//fastjson 多字段
 @Test
 public void testFastjson02() {
 String jsonStr = "{\"age\":20,\"name\":\"lisi\",\"sex\":\"男\",\"hobby\":\"basketball\"}";
 Student stu = JSON.parseObject(jsonStr, Student.class);
 System.out.println(stu); // Student [name=lisi, sex=男, age=20]
 }

再用jackson進行測試:

當字段少於實體類字段:正常通過,沒有的字段會被賦予默認值

//jackson 少字段
 @Test
 public void testJackson01() throws Exception{
 String jsonStr = "{\"age\":18,\"name\":\"zhangsan\"}";
 ObjectMapper om = new ObjectMapper();
 Student stu = om.readValue(jsonStr, Student.class);
 System.out.println(stu); // Student [name=zhangsan, sex=null, age=18]
 }

當字段多於實體類字段:

//jackson 多字段
 @Test
 public void testJackson02() throws Exception{
 String jsonStr = "{\"age\":20,\"name\":\"lisi\",\"sex\":\"男\",\"hobby\":\"basketball\"}";
 ObjectMapper om = new ObjectMapper();
 Student stu = om.readValue(jsonStr, Student.class);
 System.out.println(stu);
 }

此時會報錯,這個錯翻譯過來就是,一個無法識別的field。

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "hobby" (class com.cyj.demo03.Student), not marked as ignorable (3 known properties: "name", "sex", "age"])
 at [Source: {"age":20,"name":"lisi","sex":"男","hobby":"basketball"}; line: 1, column: 44] (through reference chain: com.cyj.demo03.Student["hobby"])
 at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:51)
 at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:817)
 at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:958)
 at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1324)
 at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1302)
 at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:249)
 at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:136)
 at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3564)
 at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2580)
 at com.cyj.demo03.TestJson.testJackson02(TestJson.java:40)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:497)
 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
 at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
 at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
 at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

由此可見,在默認情況下,jackson是不支持json串的字段多於實體類字段的,但是,jackson也提供瞭解決方案,我們在實體類上,添加註解@JsonIgnoreProperties,這個註解有一個ignoreUnknown屬性,默認值為false,我們可以將它改為true,這樣jackson在反序列化的時候,就會忽略掉不存在的屬性瞭。(@JsonIgnoreProperties(ignoreUnknown = true))

補充:json字段名不一致的問題

1.場景

項目開發過程中,有時候可能要對接第三方平臺,可能就會存在字段名不一樣的問題,而雙方的字段名不一致, 而代碼開發已經有一段時間勒,如果就因為字段名不一樣的問題,雙方改成屬性名一致,這樣改動量太大,也不保險,下面我來接手一下,針對這種場景,如果解決。

假設: 系統通過http對接,傳的是json。有一個參數”名稱”

第三方平臺:name

開發環境:userName

直接通過實體類映射,不用說肯定有問題

2.解決方法

@JsonProperty("name")
private String userName;

在實體類的屬性上增加一個註解就可以解決這種問題。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: