【发布时间】:2019-04-06 14:29:48
【问题描述】:
我已经被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
}
ShoppingCart 类
<!-- 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)。但是我无法让它工作,当我尝试使用ObjectMapper.readValue() 方法从 JSON 读取时,它给了我"main" com.fasterxml.jackson.databind.deser.UnresolvedForwardReference。
【问题讨论】:
标签: java json jackson deserialization json-deserialization