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

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

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>

以上就是如何使用Java中的Jackson库忽略空和空字段?的详细内容,更多请关注其它相关文章!