Home  >  Article  >  Java  >  In Java, how can we ignore certain fields during JSON serialization?

In Java, how can we ignore certain fields during JSON serialization?

王林
王林forward
2023-09-05 09:45:081357browse

In Java, how can we ignore certain fields during JSON serialization?

If there are fields in the Java object that we do not want to be serialized, we can use the @JsonIgnore annotation in the Jackson library . @JsonIgnore can be used to ignore fields during serialization and deserialization.

Syntax

public @interface JsonIgnore

Example

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;
   }
}

Output

{
   "EMPLOYEE_FIRST_NAME" : "Raja",
   "EMPLOYEE_LAST_NAME" : "Ramesh",
   "EMPLOYEE_ID" : 120
}

The above is the detailed content of In Java, how can we ignore certain fields during JSON serialization?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete