开发者

Deserialize self referencing objects with Jackson

开发者 https://www.devze.com 2023-04-13 06:50 出处:网络
I have a JSON string looking like that (simplified): [ { \"id\":1, \"friends\":[2] }, { \"id\":2, \"friends\":[1,3] },

I have a JSON string looking like that (simplified):

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

The content of friends are ids of开发者_Go百科 other users in the list.

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?

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. Jackson 1.9 adds two new features that might help:

  • ValueInstantiators, so you can add constructors for deserializer to convert from basic integer into 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)

However I am not 100% sure how to combine these two features for specific use case...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号