First, create a class that represents a single json object, e.g.:

class MyObject {
    private String image;

    public MyObject(String name) { image = name; }
}

Gson will use the class' variable names to determine what property names to use.

Then create an array or list of these using the data you have available, e.g.

ArrayList<MyObject> allItems = new ArrayList<>();
allItems.add(new MyObject("name1"));
allItems.add(new MyObject("name2"));
allItems.add(new MyObject("name3"));

Finally, to serialize to Json, do:

String json = new Gson().toJson(allItems);

And to get the data back from json to an array:

MyObject[] items = new Gson().fromJson(json, MyObject[].class);

For simple (de)serialization, there is no need to be dealing directly with Json classes.

Answer from Allen G on Stack Overflow
🌐
Javadoc.io
javadoc.io › doc › com.google.code.gson › gson › 2.6.2 › com › google › gson › JsonArray.html
JsonArray - gson 2.6.2 javadoc
Bookmarks · Latest version of com.google.code.gson:gson · https://javadoc.io/doc/com.google.code.gson/gson · Current version 2.6.2 · https://javadoc.io/doc/com.google.code.gson/gson/2.6.2 · package-list path (used for javadoc generation -link option) · https://javadoc.io/doc/com.goog...
🌐
HowToDoInJava
howtodoinjava.com › home › gson › gson – parse json array to java array or list
Gson - Parse JSON Array to Java Array or List
April 4, 2023 - Learn to use Google GSON library to deserialize or convert JSON, containing JSON array as root or member, to Java Array or List of objects.
🌐
Mkyong
mkyong.com › home › java › how to parse json array using gson
How to parse JSON Array using Gson - Mkyong.com
May 17, 2024 - package com.mkyong.json.gson; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.mkyong.json.gson.model.Item; import java.lang.reflect.Type; import java.util.List; public class GsonParseJsonArrayExample1 { public static void main(String[] args) { String json = """ [ { "id": 1, "name": "a" }, { "id": 2, "name": "b" } ] """; Gson gson = new Gson(); // create a List<Item> Type listItemType = new TypeToken<List<Item>>() {}.getType(); // convert json array to List<Item> List<Item> list = gson.fromJson(json, listItemType); list.forEach(System.out::println); } }
🌐
GitHub
github.com › google › gson › blob › main › gson › src › main › java › com › google › gson › JsonArray.java
gson/gson/src/main/java/com/google/gson/JsonArray.java at main · google/gson
A Java serialization/deserialization library to convert Java Objects into JSON and back - gson/gson/src/main/java/com/google/gson/JsonArray.java at main · google/gson
Author   google
🌐
Javadoc.io
javadoc.io › doc › com.google.code.gson › gson › latest › com.google.gson › com › google › gson › JsonArray.html
JsonArray - gson 2.13.2 javadoc
Bookmarks · Latest version of com.google.code.gson:gson · https://javadoc.io/doc/com.google.code.gson/gson · Current version 2.13.2 · https://javadoc.io/doc/com.google.code.gson/gson/2.13.2 · package-list path (used for javadoc generation -link option) · https://javadoc.io/doc/com.go...
🌐
Javadoc.io
javadoc.io › static › com.google.code.gson › gson › 2.10 › com.google.gson › com › google › gson › JsonArray.html
JsonArray (Gson 2.10 API)
com.google.gson.JsonArray · All Implemented Interfaces: Iterable<JsonElement> public final class JsonArray extends JsonElement implements Iterable<JsonElement> A class representing an array type in JSON. An array is a list of JsonElements each of which can be of a different type.
🌐
Tabnine
tabnine.com › home page › code › java › com.google.gson.jsonarray
com.google.gson.JsonArray java code examples | Tabnine
Gson · origin: chanjarster/weixin-java-tools · @Override public void userDelete(String[] userids) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete"; JsonObject jsonObject = new JsonObject(); JsonArray jsonArray = new JsonArray(); for (int i = 0; i < userids.length; i++) { jsonArray.add(new JsonPrimitive(userids[i])); } jsonObject.add("useridlist", jsonArray); post(url, jsonObject.toString()); } origin: aa112901/remusic ·
Find elsewhere
Top answer
1 of 9
276

You can parse the JSONArray directly, don't need to wrap your Post class with PostEntity one more time and don't need new JSONObject().toString() either:

Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = gson.fromJson(jsonOutput, listType);
2 of 9
8

I was looking for a way to parse object arrays in a more generic way; here is my contribution:

CollectionDeserializer.java:

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {

    @Override
    public Collection<?> deserialize(JsonElement json, Type typeOfT,
            JsonDeserializationContext context) throws JsonParseException {
        Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];

        return parseAsArrayList(json, realType);
    }

    /**
     * @param serializedData
     * @param type
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
        ArrayList<T> newArray = new ArrayList<T>();
        Gson gson = new Gson();

        JsonArray array= json.getAsJsonArray();
        Iterator<JsonElement> iterator = array.iterator();

        while(iterator.hasNext()){
            JsonElement json2 = (JsonElement)iterator.next();
            T object = (T) gson.fromJson(json2, (Class<?>)type);
            newArray.add(object);
        }

        return newArray;
    }

}

JSONParsingTest.java:

public class JSONParsingTest {

    List<World> worlds;

    @Test
    public void grantThatDeserializerWorksAndParseObjectArrays(){

        String worldAsString = "{\"worlds\": [" +
            "{\"name\":\"name1\",\"id\":1}," +
            "{\"name\":\"name2\",\"id\":2}," +
            "{\"name\":\"name3\",\"id\":3}" +
        "]}";

        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
        Gson gson = builder.create();
        Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);

        assertNotNull(decoded);
        assertTrue(JSONParsingTest.class.isInstance(decoded));

        JSONParsingTest decodedObject = (JSONParsingTest)decoded;
        assertEquals(3, decodedObject.worlds.size());
        assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
    }
}

World.java:

public class World {
    private String name;
    private Long id;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Converting JSON Array to Java List with Gson - Java Code Geeks
April 25, 2024 - We parse a JSON array into a JsonArray using Gson’s JsonParser. Then, we iterate over each element of the array, converting them into Java objects using Gson’s fromJson() method. Finally, we add each Java object to a List.
🌐
Javadoc.io
javadoc.io › doc › com.google.code.gson › gson › 2.8.5 › com › google › gson › JsonArray.html
JsonArray - gson 2.8.5 javadoc
Latest version of com.google.code.gson:gson · https://javadoc.io/doc/com.google.code.gson/gson · Current version 2.8.5 · https://javadoc.io/doc/com.google.code.gson/gson/2.8.5 · package-list path (used for javadoc generation -link option) https://javadoc.io/doc/com.google.code.gson/gson/2.8.5/package-list ·
🌐
TutorialsPoint
tutorialspoint.com › how-to-convert-java-array-or-arraylist-to-jsonarray-using-gson-in-java
How to convert Java array or ArrayList to JsonArray using Gson in Java?
import com.google.gson.*; import java.util.*; public class JavaArrayToJsonArrayTest { public static void main(String args[]) { String[][] strArray = {{"elem1-1", "elem1-2"}, {"elem2-1", "elem2-2"}}; ArrayList<ArrayList<String>> arrayList = new ArrayList<>(); for(int i = 0; i < strArray.length; i++) { ArrayList<String> nextElement = new ArrayList<>(); for(int j = 0; j < strArray[i].length; j++) { nextElement.add(strArray[i][j] + "-B"); } arrayList.add(nextElement); } JsonObject jsonObj = new JsonObject(); // array to JsonArray JsonArray jsonArray1 = new Gson().toJsonTree(strArray).getAsJsonArray(); // ArrayList to JsonArray JsonArray jsonArray2 = new Gson().toJsonTree(arrayList).getAsJsonArray(); jsonObj.add("jsonArray1", jsonArray1); jsonObj.add("jsonArray2", jsonArray2); System.out.println(jsonObj.toString()); } }
🌐
Tabnine
tabnine.com › home page › code › java › com.google.gson.jsonarray
com.google.gson.JsonArray.getAsJsonArray java code examples | Tabnine
public static List<Object> getJsonArrayValue(JsonArray jsonArray) { List<Object> list = new ArrayList<>(); for (JsonElement element : jsonArray.getAsJsonArray()) { list.add(resolveJsonElement(element)); } return list; } } origin: stackoverflow.com · String json = "{\"supplyPrice\": {\n" + " \"CAD\": 78,\n" + " \"CHF\": 54600.78,\n" + " \"USD\": 20735.52\n" + " }}"; Gson gson = new Gson(); JsonObject jsonObject = gson.fromJson(json, JsonObject.class); JsonObject supplyPrice = jsonObject.get("supplyPrice").getAsJsonObject(); Type type = new TypeToken<HashMap<String, Double>>() { }.getType(); Ha
Top answer
1 of 6
321

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.

2 of 6
19

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]
🌐
Google Groups
groups.google.com › g › google-gson › c › aJrqiVZTtMg
Deserialize to JsonArray causes JsonParseException (GSON-1.6)
JsonArray is an internal json element representation of an array. I don't think you can deserialize anything into JsonArray. Gson generally is used for serilizing your structures, or deserializing into your structures (your structures here means structures that you defined) In this case, there ...
🌐
Medium
medium.com › code-kings › java-json-gson-how-to-access-a-nested-array-with-gson-3067df1991ba
Java | Json | Gson → How to access a nested array with Gson | by Tony Mucci | Code Kings | Medium
January 25, 2021 - All the other tutorials say, “Just make a POJO and then inject it into your ObjectMapper”. I agree with that sentiment on certain occasions; however, I needed to process a search that is sending a JSON Request via a POST. There isn’t really a need to make a full-blown POJO for a couple of JSON elements. Below is a quick way to access a nested array in JSON using Google’s JSON library called GSON.
Top answer
1 of 2
1

I think you can do what you want without writing out a json string and then re-reading it:

List<Person> arrPersons = new ArrayList<Person>();

// populate your list

Gson gson = new Gson();
JsonElement element = gson.toJsonTree(arrPersons, new TypeToken<List<Person>>() {}.getType());

if (! element.isJsonArray()) {
// fail appropriately
    throw new SomeException();
}

JsonArray jsonArray = element.getAsJsonArray();
2 of 2
0
    public JSONArray getMessage(String response){

    ArrayList<Person> arrPersons = new ArrayList<Person>();
    try {
        // obtain the response
        JSONObject jsonResponse = new JSONObject(response);
        // get the array
        JSONArray persons=jsonResponse.optJSONArray("data");


        // iterate over the array and retrieve single person instances
        for(int i=0;i<persons.length();i++){
            // get person object
            JSONObject person=persons.getJSONObject(i);
            // get picture url
            String picture=person.optString("picture");
            // get id
            String id=person.optString("id");
            // get name
            String name=person.optString("name");

            // construct the object and add it to the arraylist
            Person p=new Person();
            p.picture=picture;
            p.id=id;
            p.name=name;
            arrPersons.add(p);
        }
        //sort Arraylist
        Collections.sort(arrPersons, new PersonSortByName());


    Gson gson = new Gson();
    //gson.toJson(arrPersons);

    String jsonString = gson.toJson(arrPersons);

    sortedjsonArray = new JSONArray(jsonString);



    } catch (JSONException e) {

        e.printStackTrace();
    }

    return sortedjsonArray;

}



public class PersonSortByName implements Comparator<Person>{

    public int compare(Person o1, Person o2) {
    return o1.name.compareTo(o2.name);
    }
    }

  public class Person{
       public String picture;
       public String id;
       public String name;
  }