首页 > 解决方案 > Jackson:尝试将 JSON 反序列化为 java 对象时未解析的前向引用

问题描述

我已经被困在一个问题上Jackson很长一段时间了,我渴望解决它。我有一个JSON对象,其中包含通过 ID 相互引用的对象,我需要将其反序列化为对象,但Unresolved forward references exception在尝试这样做时我一直在获取。

我曾尝试使用上述类的Jackson注释@JsonIdentityInfo,但这并没有产生任何结果。

JSON 示例:

{
  "customer": [
    {
      "id": 1,
      "name": "Jane Gallow",
      "age": 16
    },
    {
      "id": 2,
      "name": "John Sharp",
      "age": 20
    },
  ],
  "shoppingcart": [
    {
      "id": 1,
      "customer": 2,
      "orderDate": "2015-02-19"
    }
  ]
}

客户类


@JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id",scope = Customer.class)
@JsonIdentityReference(alwaysAsId = true)
public class Customer {

    private int id = -1;

    private String name;

    private int age;

    //getters, setters
}

购物车类


<!-- language: java -->

@JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id",scope = ShoppingCart.class)
public class ShoppingCart {

    private int id = -1;

    private Customer customer;

    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate orderDate = LocalDate.now();

    //getters, setters
}

我希望Jackson给我一个ShoppinCart对象,该对象引用Customer了 id 为2(在本例中为 John Sharp)的对象。但是我无法让它工作,"main" com.fasterxml.jackson.databind.deser.UnresolvedForwardReference当我尝试使用ObjectMapper.readValue()方法从 JSON 中读取时,它给了我。

标签: javajsonjacksondeserializationjson-deserialization

解决方案


在反序列化过程中,我遇到了与未解决的前向引用相同的问题。我使用https://www.logicbig.com/tutorials/misc/jackson/json-identity-reference.html上提供的示例来检查并解决我的问题。有一个非常简单的类:

public class Order {
  private int orderId;
  private List<Integer> itemIds;
  private Customer customer;
....
}

我在 Customer 类中添加了 @JsonCreator 静态工厂方法,它没有引起任何问题。

现在,当我向 Order 类添加任何类型的 @JsonCreator(静态方法或构造函数)时,我会立即得到未解析的前向引用。有趣的是,当我添加以下构造函数时,仅存在 @JsonPropery 注释:

 public Order(@JsonProperty("orderId") int orderId, @JsonProperty("itemIds") List<Integer> itemIds, @JsonProperty("customer") Customer customer) {
    this.orderId = orderId;
    this.itemIds = itemIds;
    this.customer = customer;
}

它还会导致无法解析的前向引用。

为了解决这个问题,对于 Order 类,您必须创建无参数构造函数(可以是私有的)。否则你会得到:

线程“主”com.fasterxml.jackson.databind.exc.InvalidDefinitionException 中的异常:无法构造实例com.logicbig.example.Order(没有创建者,如默认构造,存在):无法从对象值反序列化(没有基于委托或属性的创建者)

并且不得有任何 @JsonCreator 注释的方法和构造函数,或带有 @JsonProperty 注释的构造函数。

仅此而已。


推荐阅读