잭슨 Java용 라이브러리이며 매우 강력한 데이터 바인딩 기능을 가지고 있으며 맞춤 Java 개체를 JSON으로 직렬화하는 프레임워크를 제공합니다. JSON을 다시 Java 객체로 역직렬화 . Jackson 라이브러리는 @JsonInclude 주석을 제공합니다. 직렬화 중 해당 값을 기반으로 클래스 전체 또는 개별 필드의 직렬화를 제어합니다.
@JsonInclude 주석 2개 미만의 값을 포함합니다.
- 포함.NON_NULL :null 값이 아닌 속성만 JSON에 포함됨을 나타냅니다.
- 포함.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
}