In this post under Gson, I will explain with example the purpose of “@SerializedName” annotation.
By default when we serialize an object to Json, the class field names are used as key names in the Json.
For example if we have the below class structure
JavaBean class structure
package defaultPackage;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Author {
private String name;
private String ssn;
private String publishedName;
private List<String> bookNames;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getPublishedName() {
return publishedName;
}
public void setPublishedName(String publishedName) {
this.publishedName = publishedName;
}
public List<String> getBookNames() {
return bookNames;
}
public void setBookNames(List<String> bookNames) {
this.bookNames = bookNames;
}
}
The json output will be as shown below
{"name":"John Doe","ssn":"111-111-1111","publishedName":"John Slater","bookNames":["Othellos Revenge","Solaris"]}
As you can see from the output, the field names are used as it is as key names.
We can configure Gson, to print names other than the field names by the help of “@SerializedName” annotation.
This annotation is applied at the field level and it will take String as parameter name. The String will be used as alias name of the field on which this annotation is applied.
So for example we will annotate the field “publishedName” with “@SerializedName” annotation as shown below
@SerializedName("penName")
private String publishedName;
Now when we serialize an instance of “Author” class, we get the below output
{"name":"John Doe","ssn":"111-111-1111","penName":"John Slater","bookNames":["Othellos Revenge","Solaris"]}
As you can see from the output, the key name “publishedName” is changed to “penName” when compared with previous output.
In this way we can use “@SerializedName” annotation.