解决json串和实体类字段不一致的问题

时间:2022-10-07 21:10:23

这里我们对json串和实体类字段不一致的情况进行一个测试:

首先,我们建立一个实体类:这里简单定义了name,sex,age三个属性,以及get set tostring方法。

  1. public class Student {
  2. private String name;
  3. private String sex;
  4. private Integer age;
  5. public String getName() {
  6. return name;
  7. }
  8. public String getSex() {
  9. return sex;
  10. }
  11. public Integer getAge() {
  12. return age;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public void setSex(String sex) {
  18. this.sex = sex;
  19. }
  20. public void setAge(Integer age) {
  21. this.age = age;
  22. }
  23. @Override
  24. public String toString() {
  25. return "Student [name=" + name + ", sex=" + sex + ", age=" + age + "]";
  26. }
  27. }

首先用fastjson进行测试:

当字段少于实体类字段:正常通过,没有的字段会被赋予默认值

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

当字段多于实体类字段:正常通过,没有的字段不会被反序列化到对象中

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

再用jackson进行测试:

当字段少于实体类字段:正常通过,没有的字段会被赋予默认值

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

当字段多于实体类字段:

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

此时会报错,这个错翻译过来就是,一个无法识别的field。

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

由此可见,在默认情况下,jackson是不支持json串的字段多于实体类字段的,但是,jackson也提供了解决方案,我们在实体类上,添加注解@JsonIgnoreProperties,这个注解有一个ignoreUnknown属性,默认值为false,我们可以将它改为true,这样jackson在反序列化的时候,就会忽略掉不存在的属性了。(@JsonIgnoreProperties(ignoreUnknown = true))

解决json串和实体类字段不一致的问题

补充:json字段名不一致的问题

1.场景

项目开发过程中,有时候可能要对接第三方平台,可能就会存在字段名不一样的问题,而双方的字段名不一致, 而代码开发已经有一段时间勒,如果就因为字段名不一样的问题,双方改成属性名一致,这样改动量太大,也不保险,下面我来接手一下,针对这种场景,如果解决。

假设: 系统通过http对接,传的是json。有一个参数"名称"

第三方平台:name

开发环境:userName

直接通过实体类映射,不用说肯定有问题

2.解决方法

  1. @JsonProperty("name")
  2. private String userName;

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

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

原文链接:https://blog.csdn.net/MrHamster/article/details/85268990