【问题标题】:com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArraycom.google.gson.JsonObject 无法转换为 com.google.gson.JsonArray
【发布时间】:2020-12-13 15:19:45
【问题描述】:

我在解析 JSON 响应时遇到了一些问题。响应数据:

{
    "deal": {
        "categorie": {
            "description": "Offres Shopping",
            "idcategorie": "1",
            "nom": "Shopping"
        },
        "conditions": "2 personne au plus",
        "dateAjout": "2013-01-07T00:00:00+01:00",
        "dateExp": "2013-01-31T00:00:00+01:00",
        "description": "nuit dans un hotel 5 etoile",
        "heurexp": "12",
        "iddeal": "1",
        "minutesexp": "30",
        "prestataire": {
            "adresse": "Qu zohour 44",
            "codePostale": "12600",
            "description": "Hotel 5 etoiles",
            "idprestataire": "1",
            "nom": "Hotel ronald",
            "pays": "France",
            "telephone": "99999999",
            "ville": "Brest"
        },
        "prix": "80.0",
        "prixHabituel": "200.0",
        "tags": "hotel",
        "titre": "Nuit 5 etoiles"
    }
}

当尝试将此响应解析为 List<Deal> 时,我得到了这个异常:

com.google.gson.JsonObject 无法转换为 com.google.gson.JsonArray

这是我用于解析的代码:

if (reponse != null && !reponse.isEmpty()) {
System.out.println(reponse);

Gson g = new Gson();
JsonParser parser = new JsonParser();
JsonObject jObject = parser.parse(reponse).getAsJsonObject();
JsonArray jArray =  jObject.getAsJsonArray("deal");  // here goes the Exception
for (JsonElement elem : dealArray) {
deals.add(g.fromJson(elem, Deal.class));
}

    System.out.println(deals.toString());
    return "success";
}

谢谢

【问题讨论】:

    标签: json casting arrays


    【解决方案1】:

    好吧,deal 不是 JSON 数组,它是一个 JSON 对象。因此例外。一个 JSON 数组,供参考,看起来更像这样:

    "deal" : [{"attr" : "value"}, {"attr" : "value"}]
    

    【讨论】:

    • 是的,但是当我调用 jsonObejct.getAsJsonArray("deal") 我想获得 JsonArray 我有这个例外
    • 我不确定如何进一步分解,您无法从对象中获取 JSON 数组,因为其中没有数组。您发布的整个 JSON 中实际上没有数组。您是否正在尝试访问deal属性
    • 是的,但我使用 json Gson 的 google 库,它提供了将 jsonObject 转换为 JsonArray 的可能性,但我不知道为什么会出现此错误
    • 好的,请告诉我。在进行转换之前,将此行添加到您的代码中,并告诉我结果 - System.out.println("Is Array: " + jsonObject.get("deal").isJsonArray());
    • 我想将 JsonObject 转换为 JsonArray 以使用 new Gson().from(JsonElement,Deal.class) 创建我的对象
    猜你喜欢
    • 2019-06-17
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多