Annotation @SerializedName ของ Gson ใช้สำหรับทำซีเรียลไลซ์เป็น JSON ด้วยชื่อฟิลด์ที่กำหนดไว้ Annotation นี้สามารถลบล้าง FieldNamingPolicy ใดๆ รวมถึงนโยบายตั้งชื่อฟิลด์เริ่มต้นที่อาจตั้งค่าไว้บนอินสแตนซ์ Gson นโยบายตั้งชื่อที่แตกต่างกันสามารถตั้งค่าได้โดยใช้คลาส GsonBuilder
ไวยากรณ์
@Retention(value=RUNTIME)
@Target(value={FIELD,METHOD})
public @interface SerializedName
ตัวอย่างโค้ด
import com.google.gson.annotations.*;
import com.google.gson.*;
public class SerializedNameAnnotationTest {
public static void main(String args[]) {
Employee emp = new Employee("Rahul", "Dev", 30, "Nagpur");
Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print
String jsonStr = gson.toJson(emp);
System.out.println(jsonStr);
}
}
// คลาส Employee
class Employee {
@SerializedName("first_name")
private String firstName;
@SerializedName("last_name")
private String lastName;
private int age;
private String address;
public Employee() {}
public Employee(String firstName, String lastName, int age, String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
// Getters
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public int getAge() { return age; }
public String getAddress() { return address; }
}
ผลลัพธ์
{
"first_name": "Rahul",
"last_name": "Dev",
"age": 30,
"address": "Nagpur"
}