Gson @SerializedName एनोटेशन को प्रदान किए गए नाम मान के साथ JSON में सीरियलाइज़ किया जा सकता है जो इसका फ़ील्ड नाम है। यह एनोटेशन किसी भी 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(); // सुंदर प्रिंट String jsonStr = gson.toJson(emp); System.out.println(jsonStr); } } // Employee class 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; } 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" }