首頁  >  文章  >  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