如何使用 Gson 反序列化未知原语 json 属性 类型

How to Deserialize unknown primitive json property type using Gson

使用 Gson 反序列化简单 JSONObject(或 JSONArray)的最佳方法是什么,但是 "value" 属性 可以是整数、布尔值或字符串类型

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

和class

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

根据 Deadpool 的建议,我尝试了 JsonPrimitive 类型,但每当我想从 ViewPair 中获取值时都会出错,如下所示:

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

您可以将其解析为 JsonPrimitive since it has methods to check type isBoolean, isNumber and isString 以及获取值的方法

public class ViewPair {

   @SerializedName("label")
   private String label;

   @SerializedName("value")
   private JsonPrimitive value;

}

这是我测试这三种情况的例子

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

JsonObject可以直接得到JsonPrimitive

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

并且从 JsonPrimitive 你可以得到所需类型的值

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