4

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"
    }
}

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

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";
}

thanks

1 Answer 1

5

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"}]
Sign up to request clarification or add additional context in comments.

6 Comments

yes but when i call jsonObejct.getAsJsonArray("deal") i want to get the JsonArray i have this exception
I'm not sure how to break this down further, you can't get a JSON array from your object, because there is no array in it. There is literally no array in the entirety of the JSON you posted. Are you, perhaps, trying to access the attributes of deal?
yes but i use the google library for json Gson & it's offer that possibility transform a jsonObject to an JsonArray but i don't know why i have this error
Ok, oblige me here. Before doing the conversion, add this line to your code, and tell me the result - System.out.println("Is Array: " + jsonObject.get("deal").isJsonArray());
I want to convert the JsonObject to a JsonArray to create my object usin new Gson().from(JsonElement,Deal.class)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.