Gson how to get serialized name

When we define a class with the following format

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

for JsonObject content

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

and using Gson to analyze content

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

So my question is: can we use Gson to get the name @Serialized . In this case, I want to know that @Serialized name is used for field.name , which name and for field.category , which category .

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

 java.lang.reflect.Field fields = Field.class.getDeclaredField("name"); SerializedName sName =fields.getAnnotation(SerializedName.class); System.out.println(sName.value()); 
+7
java gson
source share
1 answer

Use reflection to get the desired Field object. Then you can use Field#getAnnotation(Class) to get an instance of SerializedName , on which you can call value() to get the name.

+9
source share

All Articles