【问题标题】:How to parse JSONArray and JSONObject with the same json key using Gson?如何使用 Gson 解析具有相同 json 键的 JSONArray 和 JSONObject?
【发布时间】:2018-09-20 05:07:06
【问题描述】:

我需要使用 Gson 将 json 字符串解析为 Java 对象(即产品)。这是我的问题:在这两种情况下,产品的 json 字符串将包含项目列表(即 json 数组)或仅包含具有相同 json 键的项目(即 json 对象)。如何在 Product 类中声明项目变量以进行如下解析?如果我声明 List 那么它在 Object 情况下失败,反之亦然。

public class Product {

@SerializedName("item-content")
@Expose
private List<Item> itemsContent = null;

  //OR 
@SerializedName("item-content")
@Expose
private Item itemContent = null;

}

这就是我如何使用 gson 将 json 转换为模型。

public static <T> T getJavaObjectFromJsonString(String jsonString, Class<T> class1) {
    T obj = null;
    try {
        obj = getGsonInstance().fromJson(jsonString, class1);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return obj;
}

public static Gson getGsonInstance() {
    if (gson == null) {
        gson = new GsonBuilder().setLenient().create();
    }
    return gson;
}

【问题讨论】:

  • 你在 Android 中使用 Gson 吗?
  • 是的,我在 Android 中使用 Gson。
  • 可以直接根据json响应字符串创建模型类

标签: android arrays json gson jsonexception


【解决方案1】:

导入 com.google.gson.JsonObject;

导入 com.google.gson.JsonParser;

JsonParser jsonParser = new JsonParser();

JsonObject jsonObj = (JsonObject) jsonParser.parse(retValue); //retValue = JSONObject

你为什么不使用 Gson 的 JsonParser?

【讨论】:

    【解决方案2】:

    你必须使用 Gson 自定义解析器:

    public class Product implements JsonDeserializer<Product> {
        private List<Item> itemsContent = null;
        private Item itemContent = null;
    
        @Override
        public Product deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
            JsonObject jsonObject = json.getAsJsonObject();
            Gson gson = new GsonBuilder().create();
            Product product = new Product();
            JsonElement itemsContent = jsonObject.get("item-content");
            if (itemsContent.isJsonObject()) this.itemsContent = gson.fromJson(itemContent, Item.class);
            else this.itemContent = gson.fromJson(itemsContent, new TypeToken<List<Item>>(){}.getType());
            return product;
        }
    }
    

    然后解析您的产品对象如下:

    new GsonBuilder().registerTypeAdapter(Product.class, new Product()).create().fromJson(response.toString(), Product.class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多