首页  >  文章  >  Java  >  在 Spring MVC 中发送 JSON 时如何从 Java 对象中排除字段?

在 Spring MVC 中发送 JSON 时如何从 Java 对象中排除字段?

Barbara Streisand
Barbara Streisand原创
2024-10-26 00:49:02479浏览

How to Exclude Fields from Java Objects When Sending JSON in Spring MVC?

从 Spring MVC 发送 JSON 时忽略 Java 对象中的字段

在 Spring MVC 应用程序中,通常希望在发送 Java 对象时有选择地排除某些字段JSON 响应。这可确保仅与客户端共享必要的信息,从而增强数据隐私并减少带宽消耗。

问题陈述

在提供的代码中,User 模型类具有createdBy、updatedBy、和加密的密码。但是,要求是在发送 JSON 响应时动态忽略这些字段。

解决方案

使用注释动态排除字段有两种方法:

1 。使用@JsonIgnoreProperties("fieldname"):

使用@JsonIgnoreProperties("fieldname")注释User类,指定应排除的字段。例如:

<code class="java">@JsonIgnoreProperties(value = {"createdBy", "updatedBy", "encryptedPwd"})
public class User {
    // ... (Class definition remains the same)
}</code>

2。在单个字段上使用@JsonIgnore:

在字段声明之前使用@JsonIgnore注释特定字段。例如:

<code class="java">public class User {
    private Integer userId;
    private String userName;
    
    @JsonIgnore
    private String encryptedPwd;
    
    // ... (Other fields remain the same)
}</code>

注意: @JsonIgnore 是推荐的方法,因为它可以更精细地控制排除哪些字段。

GitHub 示例

具体实现请参考以下 GitHub 示例:https://github.com/FasterXML/jackson-databind/issues/1416

以上是在 Spring MVC 中发送 JSON 时如何从 Java 对象中排除字段?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn