Home  >  Article  >  Java  >  How to ignore null and void fields using Jackson library in Java?

How to ignore null and void fields using Jackson library in Java?

WBOY
WBOYforward
2023-08-30 13:17:05788browse

How to ignore null and void fields using Jackson library in Java?

Jackson is a library for Java that has very powerful data binding capabilities and provides a framework to serialize custom Java objects into JSON, and deserialize the JSON back into a Java object. The Jackson library provides the @JsonInclude annotation, which can control the serialization of the entire class or its individual fields during serialization based on the value.

@JsonInclude annotation contains the following two values ​​

  • Include.NON_NULL: Indicates that only attributes with non-null values ​​are included in JSON.
  • Include.NON_EMPTY: Indicates that only attributes that are not empty are included in JSON.

Example

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
public class IgnoreNullAndEmptyFieldTest {
   public static void main(String[] args) throws JsonProcessingException {
      ObjectMapper mapper = new ObjectMapper();
      mapper.enable(SerializationFeature.INDENT_OUTPUT);
      Employee employee = new Employee(115, null, ""); // passing null and empty fields
      String result = mapper.writeValueAsString(employee);
      System.out.println(result);
   }
}
// Employee class
class Employee {
   private int id;
   @JsonInclude(Include.NON_NULL)
   private String firstName;
   @JsonInclude(Include.NON_EMPTY)<strong>
</strong>   private String lastName;
   public Employee(int id, String firstName, String lastName) {
      super();
      this.id = id;
      this.firstName = firstName;
      this.lastName = lastName;
   }
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   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;
   }
}

Output

<strong>{
 "id" : 115
}</strong>

The above is the detailed content of How to ignore null and void fields using Jackson library in Java?. 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