Using GSON to parse a JSON array

JavaArraysJsonGson

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);

class Wrapper{
	int number;
	String title;		
}

Seems to work fine. But there is an extra , Comma in your string.

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

Solution 3 - Java

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());
}

sample call:

List<Specifications> objects = GsonUtils.toList(products, Specifications.class);

Solution 4 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEduardoView Question on Stackoverflow
Solution 1 - JavaPshemoView Answer on Stackoverflow
Solution 2 - JavaNarendra PathaiView Answer on Stackoverflow
Solution 3 - JavachenyuelingView Answer on Stackoverflow
Solution 4 - Javashahzeb khanView Answer on Stackoverflow