java - 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 中读取时,它给了我。
解决方案
在反序列化过程中,我遇到了与未解决的前向引用相同的问题。我使用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 注释的构造函数。
仅此而已。
推荐阅读
- jenkins - 当我将soapui与jenkins集成时,SoapUI XML文件出现错误
- selenium-webdriver - Selenium Webdriver - iframe 下的 webelements 在 IE10 中无法识别,因为它能够在 chrome 和 firefox 中识别
- javascript - Includes() 仅在字符串的第一个单词中
- javascript - D3 v4 日期标签返回错误格式
- python - "errorMessage": "无法导入模块 'lambda_function'
- c# - 在 xsd 中同时使用扩展和普通属性
- c++ - 如何使用 net-snmp API 确定请求的 OID 是否在表中?
- regex - 我正在尝试使用正则表达式来指定字符数量。大括号不起作用
- cron - XSCRON 用于安排 xsjob
- java - Java 在对象引用返回后执行自增操作