开发者

jackson serialization, is there an annotation that indicates what sub-properties to use for a property?

I'd like to see something like this

class User {
   @JsonMask({"name", "address"})
   private Company company;
   private String name;
   //...
}
class Company {
   private String name;
   private String address;
   private Set<User> employers;
   //...
}

when a user is serialized, the output should be

{"name": "Mike", "company": {"name": "Enterprise Co.Ltd", "address": "....." }}

and the costly part Set<User> and other sub-properties is safely ignored.

I'm not quite familiar with Jackson yet, and found only @JsonIgnore to the rescue, but then I would lose all those @JsonIgnored properties for ever. Is there an elegant way to solve this?

Note: I'm using Hibernate JPA, so开发者_如何学Go in my Model classes there are lots of relations, with deep relation chains and even cyclic references, so a full JSON serialization would always lead to hell ... I googled into @JsonManagedRef and friend, but that only solve the cyclic problem, and leads to a lot of config and is not very readable.


found only @JsonIgnore to the rescue, but then I would lose all those @JsonIgnored properties for ever

By this I understand that you want the unwanted Company properties to be ignored only when serializing a User, in contrast to what should happen when otherwise serializing a Company, e.g. directly.

If it's possible to use different serializer instances, i.e., two different ObjectMapper instances, then one approach to solve this, when serializing a User, is to use a mix-in to apply @JsonIgnore as appropriate. Then don't use that same serializer and mix-in when otherwise serializing a Company.

If it's necessary to just have one serializer, then custom serialization is necessary.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜