English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

What is the use of @SerializedName annotation with Gson in Java?

@SerializedNameLes annotations peuvent être utilisées pour les champs sérialisés avec des noms différents par rapport aux noms réels des champs. Nous pouvons fournir les noms de sérialisation attendus en tant qu'attributs de commentaires, Gson peut garantir que les noms fournis sont utilisés pour lire ou écrire les champs.

Grammaire

@Retention(value=RUNTIME)
@Target(value={FIELD,METHOD})
public @interface SerializedName

Exemple

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);
   }
}
//Humain
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;
   }
}

Résultat de la sortie

{
 "id": 115,
 "name": "Raja Ramesh",
 "personAddress": "Hyderabad"
}