Gson how to get serialized name

拟墨画扇 提交于 2020-04-07 18:40:43

问题


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

回答1:


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.




回答2:


Instead of parsing with Field.class, can't you parse it into a JsonObject.class instead? Then use 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().


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:

import com.google.gson.JsonElement;

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


来源:https://stackoverflow.com/questions/24114382/gson-how-to-get-serialized-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!