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());
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With