首页 > 编程语言 > 解决json串和实体类字段不一致的问题
2021
03-16

解决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;

在实体类的属性上增加一个注解就可以解决这种问题。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持自学编程网。如有错误或未考虑完全的地方,望不吝赐教。

编程技巧