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

กำหนด Naming Convention สำหรับ JSON Field Names ใน Java ด้วย Gson

FieldNamingPolicy ใช้กำหนด Naming Convention มาตรฐานสำหรับ JSON Field Names ใช้ร่วมกับ GsonBuilder เพื่อตั้งค่า Gson Instance ให้แปลง Java Field Names เป็น JSON Field Names ตามที่ต้องการ ใช้เมธอด setFieldNamingPolicy() ของ GsonBuilder กำหนด Policy เฉพาะสำหรับ Field ระหว่าง Serialization และ Deserialization

Gson รองรับ Field Naming Policies ดังนี้:

  • FieldNamingPolicy.IDENTITY: ใช้ชื่อเหมือน Java Model ตรงๆ
  • FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES: แปลง CamelCase เป็น lower_case_with_underscores
  • FieldNamingPolicy.LOWER_CASE_WITH_DASHES: แปลง CamelCase เป็น lower-case-with-dashes
  • FieldNamingPolicy.UPPER_CAMEL_CASE: ตัวอักษรแรกของ Field Name เป็นตัวใหญ่
  • FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES: ตัวอักษรแรกใหญ่ คั่นคำด้วย Space

ตัวอย่าง: ใช้ LOWER_CASE_WITH_DASHES

import com.google.gson.*;
import java.sql.Date;
import java.time.LocalDate;

public class FieldNamingPolicyTest {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .setDateFormat("yyyy-MM-dd")
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES)
            .create();
        
        Person p = new Person("Raja", "Ramesh", 30, Date.valueOf(LocalDate.of(1988, 1, 1)));
        String jsonStr = gson.toJson(p);
        System.out.println(jsonStr);
    }
}

// Person class
class Person {
    private String fistName;
    private String lastName;
    private int _age;
    private Date dateOfBirth;
    
    public Person(String fistName, String lastName, int _age, Date dateOfBirth) {
        this.fistName = fistName;
        this.lastName = lastName;
        this._age = _age;
        this.dateOfBirth = dateOfBirth;
    }
}

ผลลัพธ์

{
  "fist-name": "Raja",
  "last-name": "Ramesh",
  "_age": 30,
  "date-of-birth": "1988-01-01"
}

สังเกต: fistName → fist-name, lastName → last-name, dateOfBirth → date-of-birth แต่ _age คงเดิม (ขึ้นต้นด้วย underscore)