首頁 > Java > java教程 > 主體

如何動態忽略 Spring MVC JSON 回應中的欄位?

Linda Hamilton
發布: 2024-10-26 15:47:02
原創
511 人瀏覽過

How to Dynamically Ignore Fields in Spring MVC JSON Responses?

在Spring MVC JSON 回應中動態忽略Java 物件中的欄位

在Spring MVC 中,您可能會遇到需要在序列化時動態忽略Java 物件中的特定字段的場景它們作為JSON。這在處理包含某些客戶端或端點的敏感或不相關資料的物件時特別有用。

考慮以下使用Hibernate 的@Entity 註解的Java 模型類別:

<code class="java">@Entity
@Table(name = "user", catalog = "userdb")
@JsonIgnoreProperties(ignoreUnknown = true)
public class User implements java.io.Serializable {

    // ... Class definition omitted for brevity
}</code>
登入後複製

在Spring MVC 中在控制器中,您從資料庫擷取User 物件並將其作為JSON 回應傳回:

<code class="java">@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/getUser/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public User getUser(@PathVariable Integer userId) throws Exception {

        User user = userService.get(userId);
        user.setCreatedBy(null);
        user.setUpdatedBy(null);
        return user;
    }
}</code>
登入後複製

預設情況下,User 物件的JSON 表示形式將​​包含其所有欄位。但是,您可能希望從某些回應中排除敏感字段,例如 cryptoPwd、createdBy 和 UpdatedBy。

實現此目的的一種方法是在傳回物件之前手動將不需要的欄位設為 null。然而,這種方法容易出錯且效率低。

更優雅的解決方案是使用 @JsonIgnoreProperties 註解。您可以使用註解中的屬性名稱來指定要忽略的欄位:

<code class="java">@Entity
@Table(name = "user", catalog = "userdb")
@JsonIgnoreProperties(ignoreUnknown = true, value = {"encryptedPwd", "createdBy", "updatedBy"})
public class User implements java.io.Serializable {

    // ... Class definition omitted for brevity
}</code>
登入後複製

使用此註釋,欄位encryptedPwd、createdBy 和updatedBy 將從JSON 表示中排除。

或者,您可以在各個字段上使用 @JsonIgnore 註釋:

<code class="java">@Entity
@Table(name = "user", catalog = "userdb")
@JsonIgnoreProperties(ignoreUnknown = true)
public class User implements java.io.Serializable {

    @JsonIgnore
    private String encryptedPwd;
    private String createdBy;

    // ... Class definition omitted for brevity
}</code>
登入後複製

透過使用 @JsonIgnore 註釋 cryptoPwd 字段,您可以明確地將其從 JSON 回應中排除。

Github 範例: [JsonIgnore 範例](https://github.com/java089/spring-mvc-exclude-fields-json)

以上是如何動態忽略 Spring MVC JSON 回應中的欄位?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!