Gson如何获取序列化名称 [英] Gson how to get serialized name
问题描述
当我们使用以下格式定义类时
When we define a class with following format
public class Field {
@SerializedName("name")
public String name;
@SerializedName("category")
public String category;
}
JsonObject
内容
{
"name" : "string",
"category" : "string",
}
并使用Gson
解析内容
Field field = new GsonBuilder().create().fromJson(
content, Field.class);
所以,我的问题是我们可以使用Gson
来获取@Serialized
名称.因为在这种情况下,我想知道@Serialized
是name
和field.category
是category
的什么名称.
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
.
根据@Sotirios Delimanolis的建议,使用Reflection
我们可以获得Serialized
名称
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());
推荐答案
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.
这篇关于Gson如何获取序列化名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!