简体   繁体   English

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;

}

for the JsonObject content对于JsonObject内容

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

and using Gson to parse the content并使用Gson解析内容

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

So,my question is can we use Gson to get the @Serialized name.所以,我的问题是我们可以使用Gson来获取@Serialized名称。 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 .在这种情况下,我想知道@Serialized名称用于field.name ,即namefield.category ,即category

As per suggested by @Sotirios Delimanolis, using Reflection we can get the Serialized name根据@Sotirios Delimanolis 的建议,使用Reflection我们可以获得Serialized名称

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.使用反射来检索您想要的Field对象。 You can then use Field#getAnnotation(Class) to get a SerializedName instance on which you can call value() to get the name.然后,您可以使用Field#getAnnotation(Class)获取一个SerializedName实例,您可以在该实例上调用value()来获取名称。

Instead of parsing with Field.class , can't you parse it into a JsonObject.class instead?不是用Field.class解析,你不能把它解析成JsonObject.class吗? Then use JsonObject.get() :然后使用JsonObject.get()

import com.google.gson.JsonObject;

Gson gson = new GsonBuilder().create();
JsonObject jsonObject = gson.fromJson(content, JsonObject.class);
String serializedName = jsonObject.get("name").getAsString();

Note that .getAsString() will return it as a String without embedded double quotes, compare this to when you call toString() .请注意, .getAsString()会将其作为没有嵌入双引号的字符串返回,将其与调用toString()时进行比较。


One thing I was trying to do was serialize an enum field, which is not an object.我试图做的一件事是序列化一个枚举字段,它不是一个对象。 In that case, you can serialize using JsonElement.class , since it's just a primitive:在这种情况下,您可以使用JsonElement.class进行序列化,因为它只是一个原语:

import com.google.gson.JsonElement;

Gson gson = new GsonBuilder().create();
JsonElement jsonElement = gson.fromJson("\"a\"", JsonElement.class);
String serializedName = jsonElement.getAsString();

Thats a way with alternate for example for a more complex example这是一种alternate ,例如用于更复杂的示例

Enum class枚举类

public enum SomeStatusCd {

    @SerializedName(
        value = "status_1",
        alternate = {"an alternate 1", "an alternate 2"}
    )
    STATUS_1("status_1")
    ....
}

get the enum from alternate从替代中获取枚举

public static SomeStatusCd getFromAlternate(String alternateFieldName){
    SomeStatusCd result = null;
    Field[] statusDeclaredFields = SomeStatusCd.class.getDeclaredFields();
    String foundEnumName = null;
    for (Field statusDeclaredField : statusDeclaredFields) {
        SerializedName annotation = statusDeclaredField.getAnnotation(SerializedName.class);
        if (annotation != null){
            String[] declaredFieldAlternates = annotation.alternate();
            for (String declaredFieldAlternate : declaredFieldAlternates) {
                if (declaredFieldAlternate.equals(alternateFieldName)){
                    foundEnumName = statusDeclaredField.getName();
                }
            }
        }
    }
    if (foundEnumName != null){
        for (SomeStatusCd enumConstant : SomeStatusCd.class.getEnumConstants()) {
            if (enumConstant.name().equals(foundEnumName)){
                result = enumConstant;
            }
        }
    }

    return result;
}

Test it测试一下

    SomeStatusCd fromAlternate = getFromAlternate("an alternate 1");
    assertSame(fromAlternate, SomeStatusCd.STATUS_1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM