首頁 > Java > java教程 > 主體

在Java中,我們如何在JSON序列化過程中忽略某些欄位?

王林
發布: 2023-09-05 09:45:08
轉載
1286 人瀏覽過

在Java中,我們如何在JSON序列化過程中忽略某些欄位?

如果Java物件中存在不希望被序列化的字段,我們可以使用@JsonIgnore註解Jackson庫中。在序列化反序列化期間,@JsonIgnore可以用來忽略欄位。

語法

public @interface JsonIgnore
登入後複製

範例

import java.io.*;
import java.util.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.*;
public class JsonIgnoreAnnotationTest {
   public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {
      Employee emp = new Employee();
      emp.setFirstName("Raja");
      emp.setLastName("Ramesh");
      emp.setEmpId(120);
      emp.getTechnologies().add("Java");
      emp.getTechnologies().add("Scala");
      emp.getTechnologies().add("Python");
      ObjectMapper mapper = new ObjectMapper();
      mapper.writerWithDefaultPrettyPrinter().writeValue(System.out, emp);
   }
}
// Employee class
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
   "firstName",
   "lastName",
   "technologies",
   "empId"
})
class Employee {
<strong>   </strong>@JsonProperty("EMPLOYEE_ID")
   private int empId;
   @JsonProperty("EMPLOYEE_FIRST_NAME")
   private String firstName;
   @JsonProperty("EMPLOYEE_LAST_NAME")
   private String lastName;
   @JsonIgnore <strong>
</strong>   private List<String> technologies = new ArrayList<>();
   public int getEmpId() {
      return empId;
   }
   public void setEmpId(int empId) {
      this.empId = empId;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public List<String> getTechnologies() {
      return technologies;
   }
   public void setTechnologies(List<String> technologies) {
      this.technologies = technologies;
   }
}
登入後複製

輸出

{
   "EMPLOYEE_FIRST_NAME" : "Raja",
   "EMPLOYEE_LAST_NAME" : "Ramesh",
   "EMPLOYEE_ID" : 120
}
登入後複製

以上是在Java中,我們如何在JSON序列化過程中忽略某些欄位?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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