简体   繁体   English

使用Jackson反序列化自引用对象

[英]Deserialize self referencing objects with Jackson

I have a JSON string looking like that (simplified): 我有一个类似的JSON字符串(简化):

[
  { "id":1, "friends":[2] },
  { "id":2, "friends":[1,3] },
  { "id":3, "friends":[] }
]

The content of friends are ids of other users in the list. 朋友的内容是列表中其他用户的ID。

Is it possible somehow to create a Java class like the one below from the JSON just with Data Binding using Jackson or do I need an intermediate step for that? 有可能以某种方式使用杰克逊的数据绑定创建一个类似下面的Java类,或者我需要一个中间步骤吗?

public class User {
  private long userid;
  private List<User> friends;
// ... getters/setters

Thanks for your help. 谢谢你的帮助。

There is no fully annotative way to do this, so you would need custom JsonSerializer / JsonDeserializer. 没有完全注释的方法,所以你需要自定义JsonSerializer / JsonDeserializer。 Jackson 1.9 adds two new features that might help: Jackson 1.9增加了两个可能有用的新功能

  • ValueInstantiators, so you can add constructors for deserializer to convert from basic integer into POJO ValueInstantiators,因此您可以为反序列化器添加构造函数以将基本整数转换为POJO
  • Value injection so you could pass additional context object (which you would need to find ids of already deserializer objects, to map then from integer to instance) 值注入,这样你就可以传递额外的上下文对象(你需要找到已经反序列化器对象的id,然后从整数映射到实例)

However I am not 100% sure how to combine these two features for specific use case... 但是,我不是100%确定如何将这两个功能结合起来用于特定用例......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM