com.google.gson.JsonObject无法转换为com.google.gson.JsonArray [英] com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArray

查看:162
本文介绍了com.google.gson.JsonObject无法转换为com.google.gson.JsonArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在解析JSON响应时遇到了一些麻烦.响应数据:

I have some trouble with parsing a JSON response. The response data:

{
    "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> 的响应时,出现此异常:

When trying to parse this response to a List<Deal> I get this exception:

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

com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArray

这是我用于解析的代码:

This is the code that I am using for the parse:

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数组,而是JSON对象.因此,例外.供参考的JSON数组如下所示:

Well, deal is not a JSON array, its a JSON object. Hence the exception. A JSON array, for reference, would look more like this:

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

这篇关于com.google.gson.JsonObject无法转换为com.google.gson.JsonArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆