Antonio Roque
Antonio Roque

Reputation: 315

java , using JsonObject parse a strange json string

with JsonObject (com.google.gson.JsonObject)

I´m having problems accessing each element like "alfa-romeo" or "aston-martin" to get the values of the property´s "pt" and "en" from "alfa-romeo" and "aston-martin"

{"options":{"alfa-romeo":{"pt":"Alfa Romeo","en":"Alfa Romeo"},"aston-martin":{"pt":"Aston Martin","en":"Aston Martin"}}}

I using this code to access "options" but with no success JsonObject jsonObject = new JsonParser().parse(strJson).getAsJsonObject();

JsonArray arr = jsonObject.getAsJsonArray("options");

where I´m getting : java.lang.ClassCastException: com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArray

can any one advise me ? Thank you Roque

Upvotes: 0

Views: 120

Answers (1)

The problem is that you are trying to get an array instead of an object:

options = {"alfa-romeo":{"pt":"Alfa Romeo","en":"Alfa Romeo"},"aston-martin":{"pt":"Aston Martin","en":"Aston Martin"}}

is an object and not an array.

JsonArray arr = jsonObject.getAsJsonArray("options");

should be:

JsonObject jsonObject = hello.getAsJsonObject("options");

PS: You might want to upgrade to a newer version of Gson, your methods are deprecated

Upvotes: 0

Related Questions