Jackson 序列化,是否有注释指示属性要使用哪些子属性?

发布于 2024-12-09 19:47:36 字数 704 浏览 1 评论 0原文

我希望看到类似的内容

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤云独去闲 2024-12-16 19:47:36

只找到了 @JsonIgnore 来救援,但随后我将永远失去所有这些 @JsonIgnore 属性

据此,我明白您希望仅在序列化 User< 时忽略不需要的 Company 属性/code>,与以其他方式序列化 Company(例如直接序列化)时应该发生的情况相反。

如果可以使用不同的序列化程序实例,即两个不同的 ObjectMapper 实例,那么在序列化 User 时解决此问题的一种方法是使用 mix-in 以酌情应用@JsonIgnore。然后,在序列化 Company 时,不要使用相同的序列化器和混合。

如果只需要一个序列化程序,则需要自定义序列化。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文