When we define a class with following format
public class Field {
@SerializedName(\"name\")
public String name;
@SerializedName(\"category\")
pub
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();
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.