Parsing JSON array into java.util.List with Gson

JavaJsonParsingGson

Java Problem Overview


I have a JsonObject named "mapping" with the following content:

{
    "client": "127.0.0.1",
    "servers": [
        "8.8.8.8",
        "8.8.4.4",
        "156.154.70.1",
        "156.154.71.1"
    ]
}

I know I can get the array "servers" with:

mapping.get("servers").getAsJsonArray()

And now I want to parse that JsonArray into a java.util.List...

What is the easiest way to do this?

Java Solutions


Solution 1 - Java

Definitely the easiest way to do that is using Gson's default parsing function fromJson().

There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType (e.g., any List), which is fromJson(JsonElement json, Type typeOfT).

In your case, you just need to get the Type of a List<String> and then parse the JSON array into that Type, like this:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();

List<String> yourList = new Gson().fromJson(yourJson, listType);

In your case yourJson is a JsonElement, but it could also be a String, any Reader or a JsonReader.

You may want to take a look at Gson API documentation.

Solution 2 - Java

Below code is using com.google.gson.JsonArray. I have printed the number of element in list as well as the elements in List

import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


public class Test {

	static String str = "{ "+ 
			"\"client\":\"127.0.0.1\"," + 
			"\"servers\":[" + 
			"    \"8.8.8.8\"," + 
			"    \"8.8.4.4\"," + 
			"    \"156.154.70.1\"," + 
			"    \"156.154.71.1\" " + 
			"    ]" + 
			"}";

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			
			JsonParser jsonParser = new JsonParser();
			JsonObject jo = (JsonObject)jsonParser.parse(str);
			JsonArray jsonArr = jo.getAsJsonArray("servers");
			//jsonArr.
			Gson googleJson = new Gson();
			ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
			System.out.println("List size is : "+jsonObjList.size());
                    System.out.println("List Elements are  : "+jsonObjList.toString());

			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

OUTPUT

List size is : 4

List Elements are  : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]

Solution 3 - Java

I read solution from official website of Gson at here

And this code for you:

    String json = "{"client":"127.0.0.1","servers":["8.8.8.8","8.8.4.4","156.154.70.1","156.154.71.1"]}";

    JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
    JsonArray jsonArray = jsonObject.getAsJsonArray("servers");

    String[] arrName = new Gson().fromJson(jsonArray, String[].class);

    List<String> lstName = new ArrayList<>();
    lstName = Arrays.asList(arrName);

    for (String str : lstName) {
        System.out.println(str);
    }    

Result show on monitor:

8.8.8.8
8.8.4.4
156.154.70.1
156.154.71.1

Solution 4 - Java

I was able to get the list mapping to work with just using @SerializedName for all fields.. no logic around Type was necessary.

Running the code - in step #4 below - through the debugger, I am able to observe that the List<ContentImage> mGalleryImages object populated with the JSON data

Here's an example:

1. The JSON

   {
    "name": "Some House",
    "gallery": [
      {
        "description": "Nice 300sqft. den.jpg",
        "photo_url": "image/den.jpg"
      },
      {
        "description": "Floor Plan",
        "photo_url": "image/floor_plan.jpg"
      }
    ]
  }

2. Java class with the List

public class FocusArea {

    @SerializedName("name")
    private String mName;

    @SerializedName("gallery")
    private List<ContentImage> mGalleryImages;
}

3. Java class for the List items

public class ContentImage {

    @SerializedName("description")
    private String mDescription;

    @SerializedName("photo_url")
    private String mPhotoUrl;

    // getters/setters ..
}

4. The Java code that processes the JSON

    for (String key : focusAreaKeys) {

        JsonElement sectionElement = sectionsJsonObject.get(key);
        FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);
    }

Solution 5 - Java

Given you start with mapping.get("servers").getAsJsonArray(), if you have access to Guava Streams, you can do the below one-liner:

List<String> servers = Streams.stream(jsonArray.iterator())
                              .map(je -> je.getAsString())
                              .collect(Collectors.toList());

Note StreamSupport won't be able to work on JsonElement type, so it is insufficient.

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
QuestionAbel CallejoView Question on Stackoverflow
Solution 1 - JavaMikOView Answer on Stackoverflow
Solution 2 - JavaPrateekView Answer on Stackoverflow
Solution 3 - JavaHoangView Answer on Stackoverflow
Solution 4 - JavaGene BoView Answer on Stackoverflow
Solution 5 - JavaAlex Moore-NiemiView Answer on Stackoverflow