Jackson 序列化,是否有注释指示属性要使用哪些子属性?
我希望看到类似的内容
class User {
@JsonMask({"name", "address"})
private Company company;
private String name;
//...
}
class Company {
private String name;
private String address;
private Set<User> employers;
//...
}
当用户被序列化时,
{"name": "Mike", "company": {"name": "Enterprise Co.Ltd", "address": "....." }}
,输出应该是,并且昂贵的部分 Set
和其他子属性被安全地忽略。
我还不太熟悉 Jackson,只找到了 @JsonIgnore 来救援,但随后我将永远失去所有这些 @JsonIgnore 属性。有没有一种优雅的方法来解决这个问题?
注意:我使用的是 Hibernate JPA,所以在我的 Model 类中有很多关系,具有深层关系链甚至循环引用,所以完整的 JSON 序列化总是会导致地狱......我用 google 搜索了 @JsonManagedRef 和朋友,但这只能解决循环问题,并导致大量配置且可读性不强。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据此,我明白您希望仅在序列化
User< 时忽略不需要的
Company
属性/code>,与以其他方式序列化Company
(例如直接序列化)时应该发生的情况相反。如果可以使用不同的序列化程序实例,即两个不同的
ObjectMapper
实例,那么在序列化User
时解决此问题的一种方法是使用 mix-in 以酌情应用@JsonIgnore
。然后,在序列化Company
时,不要使用相同的序列化器和混合。如果只需要一个序列化程序,则需要自定义序列化。
By this I understand that you want the unwanted
Company
properties to be ignored only when serializing aUser
, in contrast to what should happen when otherwise serializing aCompany
, 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 aUser
, is to use a mix-in to apply@JsonIgnore
as appropriate. Then don't use that same serializer and mix-in when otherwise serializing aCompany
.If it's necessary to just have one serializer, then custom serialization is necessary.