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

วิธีเปลี่ยนชื่อ Field ใน JSON ด้วย Jackson @JsonProperty ใน Java

Annotation @JsonProperty ของ Jackson ใช้บน Property หรือ Method ระหว่าง Serialization หรือ Deserialization JSON รับ Parameter name Optional ใช้เมื่อ Property Name ต่างจาก Key Name ใน JSON โดย Default หาก Key Name ตรงกับ Property Name จะ Map ค่าได้เลย

ตัวอย่าง: เปลี่ยน Field Name ด้วย @JsonProperty

import java.io.IOException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.JsonProperty;

public class JsonPropertyAnnotationTest {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        
        User user = new User("Sai", "Adithya", "9959984000", "0402358700");
        String data = mapper.writeValueAsString(user);
        System.out.println(data);
    }
}

// User class
class User {
    @JsonProperty("first-name")
    public String firstName;
    
    @JsonProperty("last-name")
    public String lastName;
    
    @JsonProperty("mobile-phone")
    public String mobilePhone;
    
    @JsonProperty("home_phone")
    public String workPhone;
    
    public User(String firstName, String lastName, String mobilePhone, String workPhone) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.mobilePhone = mobilePhone;
        this.workPhone = workPhone;
    }
}

ผลลัพธ์

{
  "first-name" : "Sai",
  "last-name" : "Adithya",
  "mobile-phone" : "9959984000",
  "home_phone" : "0402358700"
}

สรุป: ใช้ @JsonProperty("custom-name") กำหนด JSON Key Name ตรงกับ API Spec หรือ Naming Convention ที่ต้องการ (snake_case, kebab-case, เป็นต้น) แยกจาก Java Field Name (camelCase)