@SerializeName is used to set the key that json object will include ,however @Expose is used to decide whether the variable will be exposed for Serialisation and Deserialisation ,or not. Here's the documentation of @Expose.
Even if it's late I wanted to answer this question.
To explain it we must know what is serialization and deserialization.
serialization is converting object into json string and deserialization is converting json string into object.
Let's say we've User class with no annotations.
public class User{
private String userName;
private Integer userAge;
public User(String name, Integer age){
userName = name;
userAge = age;
}
}
And we serialize this object as below
User user = new User("Ahmed", 30);
Gson gson = new Gson();
String jsonString = gson.toJson(user);
Json string will be like this
{
"userName":"Ahmed",
"userAge":30
}
If we add annotation @SerializedName
public class User{
@SerializedName("name")
private String userName;
@SerializedName("age")
private Integer userAge;
public User(String name, Integer age){
userName = name;
userAge = age;
}
}
Json string will be like this
{
"name":"Ahmed",
"age":30
}
@Expose is used to allow or disallow serialization and deserialization.
@Expose is optional and it has two configuration parameters: serialize and deserialize. By default they're set to true.
To serialize and deserialize with @Expose we create gson object like this
Gson gsonBuilder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Below userName won't be deserialized. userName's value will be null.