Friday 11 January 2019

java - 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.fromJson(JSONSTRING, Wrapper.class);


code but I can't 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 haven't 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.


Answer



Problem is caused by comma at the end of (in your case each) JSON object placed in the array:



{
"number": "...",
"title": ".." , //<- see that comma?
}



If you remove them your data will become



[
{
"number": "3",
"title": "hello_world"
}, {
"number": "2",
"title": "hello_world"

}
]


and



Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);


should work fine.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...