【问题标题】:Deserialize JsonManagedReference on many to many relations在多对多关系上反序列化 JsonManagedReference
【发布时间】:2019-09-06 16:51:48
【问题描述】:

在多对多关系上反序列化 JsonManagedReference

杰克逊版本:2.9.7

由@JsonManagedReference/@JsonBackReference 管理的具有多对多关系的对象不能被反序列化。这最容易通过示例来展示。

public class JsonReferenceTest {
    class Customer {
        @JsonManagedReference("users")
        public Collection<User> users = new ArrayList<>();

        public String name = "company";
    }

    class User {
        @JsonBackReference("users")
        public Collection<Customer> customers = new ArrayList<>();

        public String name = "user";
    }
    ObjectMapper objectMapper = new ObjectMapper();

    @Test
    public void testDeserialize() throws IOException {
        String customer = "{\"name\":\"asdf\"}";

        objectMapper.readValue(customer, Customer.class);
    }
}

运行以下测试结果:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'users': back reference type (java.util.Collection) not compatible with managed type (com.widewail.JsonReferenceTest$Customer)
 at [Source: (String)"{"name":"asdf"}"; line: 1, column: 1]

深入研究 BeanDeserializerBase 看起来,当检查反向引用类型是否与引用类型匹配时,它没有检查反向引用端的集合的包含类型。

【问题讨论】:

    标签: spring hibernate spring-boot


    【解决方案1】:

    正如 JsonBackReference 的文档所说,您不能将它与 Collection 一起使用。

    用于指示关联属性是一部分的注释
    字段之间的双向联动;并且它的角色是“孩子”(或 “返回”)链接。属性的值类型必须是bean:不能 可以是 Collection、Map、Array 或枚举。

    您可以使用 JsonIdentityInfo 描述为here。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 2021-06-12
      • 2016-08-09
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      相关资源
      最近更新 更多