How to Deserialize unknown primitive json property type using Gson

Taha :

What is the best way to deserialize using Gson a simple JSONObject (or JSONArray) but the "value" property can be of integer, boolean or string type

{"label":"Label", "value":56}
{"label":"Label", "value":false}
{"label":"Label", "value":"string value"}

with class

public class ViewPair {
    @SerializedName("label")
    private String label;
    @SerializedName("value")
    private <Unknown> value;

As advised by Deadpool, I tried JsonPrimitive type but get error whenever I want to get a value from ViewPair like this:

Gson gson=new Gson();
List<ViewPair>data = gson.fromJson(array.toString(), listType);
JSONObject object = item.getJSONObject("value");
String spinnerLabel=object.getString("label");
JsonPrimitive spinnerValue=(JsonPrimitive) object.get("value");<-error
Caused by: java.lang.ClassCastException: java.lang.Boolean cannot be cast to com.google.gson.JsonPrimitive
Deadpool :

You can parse it as JsonPrimitive since it has methods to check type isBoolean, isNumber and isString as well as methods to get the value

public class ViewPair {

   @SerializedName("label")
   private String label;

   @SerializedName("value")
   private JsonPrimitive value;

}

Here is the example i haves test these three scenarios

ViewPair targetObject1 = new Gson().fromJson("{\"label\":\"Label\", \"value\":56}", ViewPair.class);
ViewPair targetObject2 = new Gson().fromJson("{\"label\":\"Label\", \"value\":false}", ViewPair.class);
ViewPair targetObject3 = new Gson().fromJson("{\"label\":\"Label\", \"value\":\"string value\"}", ViewPair.class);

From JsonObject you can directly get the JsonPrimitive

JsonPrimitive object = item.getAsJsonPrimitive("value");

And from JsonPrimitive you can get the value in required type

object.getAsString()
object.getAsInt()
object.getAsBoolean()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12203&siteId=1