Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 JSON 직렬화 중에 필드를 어떻게 무시할 수 있습니까?


Java 객체에 직렬화를 원하지 않는 필드가 있는 경우 @JsonIgnore 주석을 사용할 수 있습니다. 잭슨 도서관. @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 {
   @JsonProperty("EMPLOYEE_ID")
   private int empId;
   @JsonProperty("EMPLOYEE_FIRST_NAME")
   private String firstName;
   @JsonProperty("EMPLOYEE_LAST_NAME")
   private String lastName;
   @JsonIgnore 
   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
}