English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
@SerializedNameAnnotations can be used for fields that need to be serialized with different names instead of the actual field names. We can provide the expected serialization name as a comment attribute, and Gson can ensure that the provided name is used to read or write the field.
@Retention(value=RUNTIME) @Target(value={FIELD,METHOD}) public @interface SerializedName
import com.google.gson.*; import com.google.gson.annotations.*; public class SerializedNameTest { public static void main(String args[]) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); Person person = new Person(115, "Raja Ramesh", "Hyderabad") String jsonStr = gson.toJson(person); System.out.println(jsonStr); {} {} //Human class Person { @SerializedName("id") private int personId; @SerializedName("name") private String personName; private String personAddress; public Person(int personId, String personName, String personAddress) { this.personId = personId; this.personName = personName; this.personAddress = personAddress; {} public int getPersonId() { return personId; {} public String getPersonName() { return personName; {} public String getPersonAddress() { return personAddress; {} {}
Output Result
{ "id": 115, "name": "Raja Ramesh", "personAddress": "Hyderabad" {}