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