Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธี Ignore Null และ Empty Fields ด้วย Jackson @JsonInclude ใน Java

Jackson ให้ Annotation @JsonInclude ควบคุม Serialization ของ Class ทั้งหมด หรือ Field เฉพาะ ตามค่าของ Field ระหว่าง Serialization

@JsonInclude มี 2 ค่าหลัก:

  • Include.NON_NULL: Include เฉพาะ Property ที่ไม่ใช่ Null
  • Include.NON_EMPTY: Include เฉพาะ Property ที่ไม่ใช่ Empty (Null, Empty String, Empty Collection, เป็นต้น)

ตัวอย่าง: Ignore Null และ Empty Fields

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);
        
        // ส่ง firstName = null, lastName = "" (empty string)
        Employee employee = new Employee(115, null, "");
        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) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    // getters, setters...
}

ผลลัพธ์

{
  "id" : 115
}

อธิบาย: firstName เป็น Null → ถูก Exclude โดย NON_NULL, lastName เป็น Empty String → ถูก Exclude โดย NON_EMPTY เหลือแค่ id เท่านั้น

Tip: วาง @JsonInclude ที่ Class Level ได้เลย เพื่อ Apply ให้ทุก Field ใน Class