What is the basic purpose of @SerializedName annotation in Android using Gson

What is the basic purpose of @SerializedName annotation in Android using Gson?

Give me some different examples. I can't understand the main purpose of using it.


Solution 1:

Java class example,

public class Person {

    @SerializedName("name")
    private String personName;

    @SerializedName("bd")
    private String birthDate;

}

This class has two fields that represent the person name and birth date of a person. These fields are annotated with the @SerializedName annotation. The parameter (value) of this annotation is the name to be used when serialising and deserialising objects. For example, the Java field personName is represented as name in JSON.

JSON Example,

{
    "name":"chintan",
    "bd":"01-01-1990"
}

Solution 2:

There are already few answers here,but I would like to add that if you are using ProGuard to Obfuscate your code & don't use @SerializedName("name") in your model class, then your GSON won't work. Because due to obfuscation, your variable names might have changed from String name to String a resulting into broken GSON parsing as GSON will look for key a into json & it will fail.

By specifying @SerializedName, GSON will not look in json based on variable name & will just use specified @SerializedName.

Of Course you can tell proguard to not obfuscate your model, but if you would like to have model obfuscated, then you must specify @SerializedName