Saturday, 24 August 2013

Using GSON to parse a JSON array

Using GSON to parse a JSON array

I have a JSON file like this:
[{ "number" : "3",
"title" : "hello_world",
},
{ "number" : "2",
"title" : "hello_world",
}]
Before when files had a root element i would use:
Wrapper w = gson.ftomJson(JSONSTRING, Wrapper.class);
code but i cant think how to code the Wrapper class as the root element is
an array
I have tried using:
Wrapper[] wrapper = gson.fromJson(jsonLine, Wrapper[].class);
with:
public class Wrapper{
String number;
String title;
}
But havent had any luck. How else can i read this using this method?
P.S i have got this to work using:
JsonArray entries = (JsonArray) new JsonParser().parse(jsonLine);
String title = ((JsonObject)entries.get(0)).get("title");
but i would prefer to know how to do it (if possible) with both methods

No comments:

Post a Comment