Gson如何获取序列化名称 [英] Gson how to get serialized name

查看:257
本文介绍了Gson如何获取序列化名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们使用以下格式定义类时

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名称.因为在这种情况下,我想知道@Serializednamefield.categorycategory的什么名称.

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()); 

推荐答案

使用反射来检索所需的Field对象.然后,您可以使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆