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

วิธีแปลง Java Object เป็น JSON ด้วย Jackson Library

JSON (JavaScript Object Notation) รูปแบบข้อมูล текст-based 輕量級 สำหรับ data interchange ไลบรารี Java หลายตัวจัดการ JSON ได้ Jackson เป็นที่นิยม: เร็ว, ใช้หน่วยความจำน้อย, API ง่าย

Dependency (Maven)


<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.15.2</version> <!-- ใช้ version ล่าสุด -->
</dependency>

คลาสหลัก: ObjectMapper

ObjectMapper เป็น entry point ของ Jackson ใช้ serialize (Object → JSON) และ deserialize (JSON → Object)

  • writeValueAsString(obj) - Object → JSON String
  • writeValue(File, obj) - Object → File
  • readValue(json, Class) - JSON → Object

ตัวอย่างโค้ดครบถ้วน


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

class Student {
    private int id;
    private String name;
    private int age;
    private long phone;
    
    // Getters & Setters (required for Jackson)
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
    public long getPhone() { return phone; }
    public void setPhone(long phone) { this.phone = phone; }
}

public class JacksonObjectToJson {
    public static void main(String[] args) throws Exception {
        Student std = new Student();
        std.setId(1);
        std.setName("Krishna");
        std.setAge(30);
        std.setPhone(9848022338L);
        
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT); // pretty print
        
        String jsonString = mapper.writeValueAsString(std);
        System.out.println(jsonString);
    }
}

ผลลัพธ์


{
  "id" : 1,
  "name" : "Krishna",
  "age" : 30,
  "phone" : 9848022338
}

Annotations ที่นิยมใช้

Annotationใช้สำหรับ
@JsonProperty("name")เปลี่ยนชื่อ field ใน JSON
@JsonIgnoreข้าม field นี้
@JsonFormat(pattern="yyyy-MM-dd")format Date
@JsonInclude(Include.NON_NULL)ไม่ serialize null values
@JsonPropertyOrder({"id", "name"})กำหนดลำดับ field

ตัวอย่างใช้ Annotations


class Student {
    @JsonProperty("student_id")
    private int id;
    
    @JsonProperty("full_name")
    private String name;
    
    @JsonIgnore
    private String password; // ไม่ serialize
    
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate dob;
    
    // getters/setters...
}

การตั้งค่า ObjectMapper แบบ Global


ObjectMapper mapper = new ObjectMapper()
    .enable(SerializationFeature.INDENT_OUTPUT)
    .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
    .setSerializationInclusion(JsonInclude.Include.NON_NULL)
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

ข้อควรระวัง

  • Class ต้องมี no-args constructor (หรือใช้ @JsonCreator)
  • Field ต้องมี getter (หรือ public field)
  • ใช้ mapper.writerWithDefaultPrettyPrinter() สำหรับ pretty print ชั่วคราว
  • Thread-safe: ObjectMapper สร้างครั้งเดียว reuse ได้ (immutable configuration)

สรุป

Jackson เป็น standard สำหรับ JSON ใน Java ใช้ ObjectMapper.writeValueAsString(object) แปลง Object → JSON String ได้ง่ายและเร็ว