Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson how to get serialized name

Tags:

java

gson

When we define a class with following format

public class Field {
    @SerializedName("name")
    public String name;
    @SerializedName("category")
    public String category;

}

for the JsonObject content

{
    "name" : "string",
    "category" : "string",
}

and using Gson to parse the content

Field field = new GsonBuilder().create().fromJson(
                content, Field.class);

So,my question is can we use Gson to get the @Serialized name. For in this instance I want to know what @Serialized name is used for field.name,which is name and for field.category which is category.

As per suggested by @Sotirios Delimanolis, using Reflection we can get the Serialized name

java.lang.reflect.Field fields = Field.class.getDeclaredField("name");             
SerializedName sName =fields.getAnnotation(SerializedName.class);            
System.out.println(sName.value()); 
like image 993
laaptu Avatar asked Jun 09 '14 05:06

laaptu


People also ask

What is serialized name?

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.

How do you serialize with Gson?

Serialization in the context of Gson means converting a Java object to its JSON representation. In order to do the serialization, we need to create the Gson object, which handles the conversion. Next, we need to call the function toJson() and pass the User object. Program output.

What is @SerializedName in spring boot?

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.


1 Answers

Use reflection to retrieve the Field object you want. You can then use Field#getAnnotation(Class) to get a SerializedName instance on which you can call value() to get the name.

like image 62
Sotirios Delimanolis Avatar answered Nov 01 '22 23:11

Sotirios Delimanolis