Jackson là thư viện Java với data binding mạnh mẽ, serialize đối tượng Java sang JSON và deserialize ngược lại. Jackson cung cấp @JsonInclude annotation kiểm soát serialization của class hoặc field riêng lẻ dựa trên giá trị của chúng khi serialize.
@JsonInclude chứa 2 giá trị chính:
- Include.NON_NULL: Chỉ include property có giá trị không null vào JSON.
- Include.NON_EMPTY: Chỉ include property không rỗng (non-null, non-empty collection/array/String) vào JSON.
Ví dụ minh họa
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, ""); // truyền null và empty
String result = mapper.writeValueAsString(employee);
System.out.println(result);
}
}
// Lớp Employee
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; }
}
Kết quả đầu ra
{ "id" : 115 }
Giải thích: firstName=null bị loại (NON_NULL), lastName="" rỗng bị loại (NON_EMPTY), chỉ còn id. Có thể đặt @JsonInclude ở cấp class để áp dụng cho toàn bộ field.