Gson how to get serialized name

后端 未结 2 858
执念已碎
执念已碎 2021-02-07 08:44

When we define a class with following format

public class Field {
    @SerializedName(\"name\")
    public String name;
    @SerializedName(\"category\")
    pub         


        
相关标签:
2条回答
  • 2021-02-07 08:58

    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();
    
    0 讨论(0)
  • 2021-02-07 09:01

    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.

    0 讨论(0)
提交回复
热议问题