![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What to use @SerializedName annotation using Gson in Java?
The @SerializedName annotation can be used to serialize a field with a different name instead of an actual field name. We can provide the expected serialized name as an annotation attribute, Gson can make sure to read or write a field with the provided name.
Syntax
@Retention(value=RUNTIME) @Target(value={FIELD,METHOD}) public @interface SerializedName
Example
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); } } // Person class 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
{ "id": 115, "name": "Raja Ramesh", "personAddress": "Hyderabad" }
Advertisements