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 the files had a root element, I would use:

 Wrapper w = gson.fromJson(JSONSTRING, Wrapper.class); 

the code, but I can't think of how to code the Wrapper class since the root element is an array.

I tried using:

 Wrapper[] wrapper = gson.fromJson(jsonLine, Wrapper[].class); 

from:

 public class Wrapper{ String number; String title; } 

But no luck. How else can I read this using this method?

PS I got this to work with:

 JsonArray entries = (JsonArray) new JsonParser().parse(jsonLine); String title = ((JsonObject)entries.get(0)).get("title"); 

But I would rather know how to do it (if possible) with both methods.

+107
java json arrays gson
Aug 24 '13 at 18:17
source share
3 answers

The problem is caused by a comma at the end (in each case of each) of the JSON object placed in the array:

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

If you delete 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.

+107
Aug 24 '13 at 18:54
source share
 Gson gson = new Gson(); Wrapper[] arr = gson.fromJson(str, Wrapper[].class); class Wrapper{ int number; String title; } 

Everything seems to be fine. But your line has an extra comma.

 [ { "number" : "3", "title" : "hello_world" }, { "number" : "2", "title" : "hello_world" } ] 
+39
Aug 24 '13 at 19:01
source share
 public static <T> List<T> toList(String json, Class<T> clazz) { if (null == json) { return null; } Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<T>(){}.getType()); } 

Call example:

 List<Specifications> objects = GsonUtils.toList(products, Specifications.class); 
+15
Nov 10 '16 at 8:10
source share



All Articles