Maison  >  Article  >  Java  >  Comment ignorer les champs nuls et non avenus à l'aide de la bibliothèque Jackson en Java ?

Comment ignorer les champs nuls et non avenus à l'aide de la bibliothèque Jackson en Java ?

WBOY
WBOYavant
2023-08-30 13:17:05784parcourir

Comment ignorer les champs nuls et non avenus à laide de la bibliothèque Jackson en Java ?

Jackson是一个用于Java的库,它具有非常强大的数据绑定能力,并提供了一个框架,可以将自定义的Java对象序列化为JSON,并将JSON反序列化回Java对象。Jackson库提供了@JsonInclude注解,它可以根据值在序列化期间控制整个类或其各个字段的序列化。

@JsonInclude注解包含以下两个值

  • Include.NON_NULL:表示仅包含具有非空值的属性在JSON中。
  • Include.NON_EMPTY:表示仅包含不为空的属性在JSON中。

示例

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

输出

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer