如何使用 Java 中的 Jackson 库忽略空和 null 字段?\n


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

@JsonInclude 注释包含以下两个值

  • Include.NON_NULL:表示仅包含非 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)
   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;
   }
}

输出

{
 "id" : 115
}

更新于: 06-Jul-2020

2K+ 次浏览

启动你的 职业生涯

通过完成课程获得认证

立即开始
广告
© . All rights reserved.