Annotation @JsonInclude ของ Jackson ใช้สำหรับ ยกเว้น คุณสมบัติ (properties) หรือ ฟิลด์ของคลาส ภายใต้เงื่อนไขบางอย่าง และสามารถกำหนดได้โดยใช้ enum JsonInclude.Include Enum JsonInclude.Include มีค่าคงที่บางอย่าง เช่น "ALWAYS", "NON_DEFAULT", "NON_EMPTY" และ "NON_NULL" เพื่อตัดสินใจว่าจะยกเว้นคุณสมบัติ (ฟิลด์) หรือไม่
ไวยากรณ์
public static enum JsonInclude.Include extends Enum<JSonInclude.Include>
ตัวอย่างโค้ด
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import java.io.*;
public class JsonIncludeTest {
public static void main(String args[]) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Employee emp = new Employee();
String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
System.out.println(jsonString);
}
}
// คลาส Employee
@JsonInclude(JsonInclude.Include.NON_EMPTY)
class Employee {
public int empId = 115;
public String empName = null;
@Override
public String toString() {
return "Employee{" +
"empId=" + empId +
", empName='" + empName + '\'' +
'}';
}
}
ผลลัพธ์
{
"empId" : 115
}