Parsing JSON array into java.util.List with Gson

gson parse json array
convert json array to java list of objects
jsonarray to list java
how to parse json array in java
gson read json array from file
gson.fromjson json array
how to convert json string to list of objects in java using gson
json parse list of objects java

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?

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.

Parsing JSON array into java.util.List with Gson, 2.2 Gson convert above JSON array into a List<Item> containing List<ItemType> types . Item.java. package com.mkyong; import java.util� Parse JSON array as member Gson parses JSON arrays as members without difficulty if they are non-root objects. We can use the fromJson () method in usual manner and it will parse the json array correctly to required java array or list.

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]

Gson - How to parse JSON Arrays, an array of arrays, How to convert Java object to / from JSON (Gson)? convert gson fromjson to map, gson fromjson to list, json fromjson to array, json string to arraylist in java. import java.util. How to Read JSON Object From File in Java? If your JSON array is stored in a JSON file, you can still read and parse its content to a list of Java Objects using Gson, as shown below: List<User> users = new Gson ().fromJson (new FileReader ("users.json"), new TypeToken<List<User>> () {}.getType ());

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

How to use Gson -> fromJson() to convert the specified JSON into an , How to use. getAsJsonArray. method. in. com.google.gson.JsonArray jelement = new JsonParser().parse(getJsonData(lang)); JsonObject jobject = jelement. List<Object> list = new ArrayList<>(); for (JsonElement element : jsonArray. 2.2 Gson convert above JSON array into a List<Item> containing List<ItemType> types. Item.java package com.mkyong; import java.util.List; public class Item { private int id; private String name; private List<ItemType> types; }

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

com.google.gson.JsonArray.getAsJsonArray java code examples , Gson tutorial shows how to work with JSON in Java using Gson library. We use three different It is easy for humans to read and write and for machines to parse and generate. It is less The following example writes a list of JSON objects into a file. GsonWriteList. ArrayList; import java.util.List; class Item� Using the Gson library, how do I convert a JSON string to an ArrayList of a custom class JsonLog? Basically, JsonLog is an interface implemented by different kinds of logs made by my Android app--SMS

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.

Gson tutorial, OutputStreamWriter; import java.util. beginArray(); // "cities": [ for(String c : emp. Converting java object to JSON is comparatively easy than parsing with Gson streaming API. how to loop through multiple employees using a class based list of objects. Welcome to Gson Example Tutorial. In last post we looked at the Java JSON API and you can easily tell that it’s not convenient to use it. Whether you have to convert JSON to Java Object or otherwise, you need to write a lot of code that is tightly coupled with the JSON structure.

Gson Example Tutorial Parse JSON, Java can keep them as separate classes and just hold a reference to the List or Array implementation. JSON needs to keep the lists as a local,� Gson has special handling for deserializing some single-component arrays into a non-array type. For example, int data = gson.fromJson("[3]", int.class); would assign the int value 3 to data. Of course, deserializing a single-component array into a non-array type is not required.

Gson — Mapping of Arrays and Lists of Objects, The Gson library can be used to parse a JSON String into a Tree Model. method of JsonElement can be used to get the element as JsonObject and getAsJsonArray() method of import java.util.List; import com.google.gson. A Json array is an ordered collection of values that are enclosed in square brackets i.e. it begins with ‘[’ and ends with ‘]’. The values in the arrays are separated by ‘,’ (comma).

How to parse a JSON to Gson Tree Model in Java?, We can parse this array into a Custom Tweets (tweets list container) object manually, but it is easier to do it with fromJson method: Gson gson = new Gson(); � Gson provide simple toJson() and fromJson() methods to convert Java objects to / from JSON.. toJson() – Java object to JSON Gson gson = new Gson(); // 1. Java object to JSON file gson.toJson(obj, new FileWriter("C:\\fileName.json")); // 2.

Comments
  • Possible duplicate of Easy way to change Iterable into Collection or Convert Iterator to ArrayList.
  • @ruakh there are many differences between that one and this question. This one deals with Gson.
  • @AbelMelquiadesCallejo have a look at answer.I hope it will solve your problem.
  • @ruakh yes I agree with you and I know JsonArray implements Iterable. It's just that I'm also finding new ways other than adding a new library.
  • Type can be found in what package?
  • Type is a Java built-in interface located in the package java.lang.reflect
  • I had to use getString() instead of get() or else .fromJson() was complaining.
  • @MikO I have a similar question with Gson here. I wanted to see if you can help me out. I do have a solution but the problem is it looks very messy just to parse a JSON into a Map.
  • same answer as the above -- still using the static method new Gson().fromJson()
  • well my problem was other but your snippet solve my problem. I stored the list of string but I wanna fetch the strings. Then your snippet recall me of their I can put String[].class to fetch data. Thank you