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

ความสำคัญของ @JsonUnwrapped annotation ใน Jackson (Java)

คำอธิบายประกอบ @JsonUnwrapped ใช้สำหรับ "unwrap" ค่าระหว่างกระบวนการ serialization และ deserialization ช่วยให้ค่าของ composed class (คลาสที่ประกอบขึ้น) แสดงผลเหมือนเป็นส่วนหนึ่งของ parent class

Syntax

@Target(value={ANNOTATION_TYPE, FIELD, METHOD, PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonUnwrapped

ตัวอย่างการใช้งาน

import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;

public class JsonUnwrappedAnnotationTest {
    public static void main(String args[]) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Employee());
        System.out.println(jsonString);
    }
}

class Employee {
    public int empId = 110;
    public String empName = "Raja Ramesh";
    
    @JsonUnwrapped
    public Address address = new Address();
    
    // Address class (inner class)
    public static class Address {
        public String doorNumber = "1118";
        public String street = "madhapur";
        public String pinCode = "500081";
        public String city = "Hyderabad";
    }
}

ผลลัพธ์ (Output)

{
  "empId" : 110,
  "empName" : "Raja Ramesh",
  "doorNumber" : "1118",
  "street" : "madhapur",
  "pinCode" : "500081",
  "city" : "Hyderabad"
}

คำอธิบาย

โดยปกติถ้าไม่มี @JsonUnwrapped JSON จะมีโครงสร้างเป็น nested object:

{
  "empId": 110,
  "empName": "Raja Ramesh",
  "address": {
    "doorNumber": "1118",
    "street": "madhapur",
    "pinCode": "500081",
    "city": "Hyderabad"
  }
}

แต่ด้วย @JsonUnwrapped ฟิลด์ของ Address จะถูก "ยกขึ้นมา" รวมอยู่ในระดับเดียวกับ Employee ทำให้ JSON แสดงผลแบบแบน (flattened)

กรณีการใช้งาน (Use Cases)

  • เมื่อต้องการรวมข้อมูลจากคลาสย่อย (composed class) เข้ากับ JSON หลัก
  • ลดความซ้อนซ้อนของโครงสร้าง JSON
  • เมื่อ API ต้องการรูปแบบ JSON แบบแบน (flat structure)

สรุป

@JsonUnwrapped เป็นเครื่องมือที่มีประโยชน์สำหรับการปรับรูปแบบ JSON ให้ตรงตามความต้องการของ API หรือ frontend โดยไม่ต้องเปลี่ยนโครงสร้างคลาส Java