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

List<Contact> contacts;    
Type listType = new TypeToken<List<Contact>>() {
                    }.getType();
 contacts= new Gson().fromJson(jsonArray, listType);

This should work. make sure that your model class has same name as of json parameters and datatype. it will parse the jsonarray to type List of java

Answer from Sahil Manchanda on Stack Overflow
Top answer
1 of 3
5

Actually you don't need the following line:

jsonObject.put("result", jsonArray);

Just use the existing jsonArray like the following:

String jsonResp = jsonArray.toString();

One other note. you will get extra " " in your response and that is because of jsonArray.put(i, string); statement in the for loop which inserts extra " ". you can simply use the following to fix that:

    jsonResp = jsonResp.replaceAll("\"[{]", "{");
    jsonResp = jsonResp.replaceAll("[}]\"", "}");
2 of 3
0

Make a Model like This DocInfoModel.java ->

public class DocInfoModel {

        @SerializedName("doc_no")
        @Expose
        private String docNo;
        @SerializedName("itembarcode")
        @Expose
        private String itembarcode;
        @SerializedName("net_wt")
        @Expose
        private String netWt;
        @SerializedName("gross_wt")
        @Expose
        private String grossWt;
        @SerializedName("stone_amt")
        @Expose
        private String stoneAmt;
        @SerializedName("rate")
        @Expose
        private String rate;
        @SerializedName("making")
        @Expose
        private String making;
        @SerializedName("qty")
        @Expose
        private String qty;
        @SerializedName("net_rate")
        @Expose
        private String netRate;
        @SerializedName("item_total")
        @Expose
        private String itemTotal;
        @SerializedName("sum_total")
        @Expose
        private String sumTotal;
        @SerializedName("stone_wt")
        @Expose
        private String stoneWt;

        /**
         *
         * @return
         * The docNo
         */
        public String getDocNo() {
            return docNo;
        }

        /**
         *
         * @param docNo
         * The doc_no
         */
        public void setDocNo(String docNo) {
            this.docNo = docNo;
        }

        /**
         *
         * @return
         * The itembarcode
         */
        public String getItembarcode() {
            return itembarcode;
        }

        /**
         *
         * @param itembarcode
         * The itembarcode
         */
        public void setItembarcode(String itembarcode) {
            this.itembarcode = itembarcode;
        }

        /**
         *
         * @return
         * The netWt
         */
        public String getNetWt() {
            return netWt;
        }

        /**
         *
         * @param netWt
         * The net_wt
         */
        public void setNetWt(String netWt) {
            this.netWt = netWt;
        }

        /**
         *
         * @return
         * The grossWt
         */
        public String getGrossWt() {
            return grossWt;
        }

        /**
         *
         * @param grossWt
         * The gross_wt
         */
        public void setGrossWt(String grossWt) {
            this.grossWt = grossWt;
        }

        /**
         *
         * @return
         * The stoneAmt
         */
        public String getStoneAmt() {
            return stoneAmt;
        }

        /**
         *
         * @param stoneAmt
         * The stone_amt
         */
        public void setStoneAmt(String stoneAmt) {
            this.stoneAmt = stoneAmt;
        }

        /**
         *
         * @return
         * The rate
         */
        public String getRate() {
            return rate;
        }

        /**
         *
         * @param rate
         * The rate
         */
        public void setRate(String rate) {
            this.rate = rate;
        }

        /**
         *
         * @return
         * The making
         */
        public String getMaking() {
            return making;
        }

        /**
         *
         * @param making
         * The making
         */
        public void setMaking(String making) {
            this.making = making;
        }

        /**
         *
         * @return
         * The qty
         */
        public String getQty() {
            return qty;
        }

        /**
         *
         * @param qty
         * The qty
         */
        public void setQty(String qty) {
            this.qty = qty;
        }

        /**
         *
         * @return
         * The netRate
         */
        public String getNetRate() {
            return netRate;
        }

        /**
         *
         * @param netRate
         * The net_rate
         */
        public void setNetRate(String netRate) {
            this.netRate = netRate;
        }

        /**
         *
         * @return
         * The itemTotal
         */
        public String getItemTotal() {
            return itemTotal;
        }

        /**
         *
         * @param itemTotal
         * The item_total
         */
        public void setItemTotal(String itemTotal) {
            this.itemTotal = itemTotal;
        }

        /**
         *
         * @return
         * The sumTotal
         */
        public String getSumTotal() {
            return sumTotal;
        }

        /**
         *
         * @param sumTotal
         * The sum_total
         */
        public void setSumTotal(String sumTotal) {
            this.sumTotal = sumTotal;
        }

        /**
         *
         * @return
         * The stoneWt
         */
        public String getStoneWt() {
            return stoneWt;
        }

        /**
         *
         * @param stoneWt
         * The stone_wt
         */
        public void setStoneWt(String stoneWt) {
            this.stoneWt = stoneWt;
        }

    }

And Parse the json by GSON ->

Gson gson = new Gson();
DocInfoModel[] docModel = gson.fromJson(RESPONSE_STRING,DocInfoModel[].class);
🌐
Crunchify
crunchify.com › json tutorials › how to use gson -> fromjson() to convert the specified json into an object of the specified class
How to use Gson -> fromJson() to convert the specified JSON into an Object of the Specified Class • Crunchify
February 16, 2023 - package crunchify.com.tutorials; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONObject; import com.google.gson.Gson; /** * @author Crunchify.com * Gson() -> fromJson() to deserializes the specified Json into an object of the specified class */ public class CrunchifyGoogleGSONExample { public static void main(String[] args) { JSONArray array = readFileContent(); convertJSONArraytoArrayList(array); } private static void convertJSONArraytoArrayList(JSONArray array) { // Use method fromJson() to deserializes the
🌐
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.
🌐
HowToDoInJava
howtodoinjava.com › home › gson › gson jsonparser
Gson JsonParser (with Examples) - HowToDoInJava
April 4, 2023 - We can convert the JsonElement to JsonObject and JsonArray using respective methods: JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonArray jsonArray = jsonElement.getAsJsonArray(); Once we have a JsonObject or JsonArray instances, ...
🌐
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 ... 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 ...
🌐
Tabnine
tabnine.com › home page › code › java › com.google.gson.jsonarray
com.google.gson.JsonArray.getJsonObject java code examples | Tabnine
Best Java code snippets using com.google.gson.JsonArray.getJsonObject (Showing top 9 results out of 315) · JsonArray jsoncargo = jsonObject.getJsonArray("cargo"); Map<String, Integer> cargo = new HashMap<>(); for (int i = 0; i < jsoncargo.size(); i++) { String type = jsoncargo.getJsonObje...
🌐
Baeldung
baeldung.com › home › json › convert string to jsonobject with gson
Convert String to JsonObject with Gson | Baeldung
May 5, 2025 - In our second approach, we’ll see how to create a Gson instance and use the fromJson method. This method deserializes the specified JSON String into an object of the specified class: public <T> T fromJson(String json, Class<T> classOfT) throws ...
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;
    }

}
Find elsewhere
🌐
Tabnine
tabnine.com › home page › code › java › com.google.gson.jsonarray
com.google.gson.JsonArray.getAsJsonArray java code examples | Tabnine
public static List<Object> ... + " \"CAD\": 78,\n" + " \"CHF\": 54600.78,\n" + " \"USD\": 20735.52\n" + " }}"; Gson gson = new Gson(); JsonObject jsonObject = gson.fromJson(json, JsonObject.class); JsonObject supplyPrice ...
🌐
Stack Overflow
stackoverflow.com › questions › 31622973 › using-gson-to-parse-jsonarray-and-jsonobject
arrays - Using gson to parse jsonarray and jsonobject - Stack Overflow
327 Gson: Directly convert String to JsonObject (no POJO) 519 Deserialize a List<T> object with Gson? 92 How to Parse JSON Array with Gson · 43 How to modify values of JsonObject / JsonArray directly? 1258 Reference - What does this error mean in PHP? 0 Parse different objects with same tag in JSON string using GSON ·
Top answer
1 of 7
4

Hope this part of code to help you:

    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();
    HashMap<String, Double> parsedJson = gson.fromJson(supplyPrice, type);
    JsonArray jsonArray = new JsonArray();
    for(String key : parsedJson.keySet()) {
        JsonObject jo = new JsonObject();
        jo.addProperty("name", key);
        jo.addProperty("value", parsedJson.get(key));
        jsonArray.add(jo);
    }
    JsonObject result = new JsonObject();
    result.add("supplyPrice", jsonArray.getAsJsonArray());
2 of 7
3

GSON uses POJO classes to parse JSON into java objects.

Create A java class containing variables with names and datatype same as keys of JSON object. I think the JSON you are getting is not in the right format.

Class SupplyPrice{
 double CAD;
 double CHF;
 double TRY
}

Class SupplyPriceContainer{
 ArrayList<SupplyPrice> supplyPrice;
}

And your JSON should be

 {
    "CAD": 78,
    "CHF": 54600.78,
    "USD": 20735.52
 }



{
    "supplyPrice": [{
        "CAD": 78,
        "CHF": 0,
        "USD": 0
    }, {
        "CAD": 0,
        "CHF": 54600.00,
        "USD": 0
    }, {
        "CAD": 0,
        "CHF": 0,
        "USD": 20735.52
    }]
 }

Then you can Use GSON's `fromJson(String pJson, Class pClassType) to convert to JAVA object

  Gson gson = new Gson()
  ArrayList<SupplyPrice> suplyPrices = gson.fromJson(pJsonString, SupplyPrice.class);

Now you can use the arraylist to get the data.

🌐
ZetCode
zetcode.com › java › gson
Java Gson - JSON serialization and deserialization in Java with Gson
October 10, 2024 - Gson is a Java serialization/deserialization library to convert Java Objects into JSON and back.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Converting a JSON Object to a JSON Array in Java - Java Code Geeks
August 1, 2025 - // ManualJsonConversion.java import ... fruitMap.put("apple", 10); fruitMap.put("banana", 20); fruitMap.put("cherry", 30); JsonArray array = new JsonArray(); for (Map.Entry<String, Integer> entry : fruitMap.entrySet()) { JsonObject obj ...
🌐
Mkyong
mkyong.com › home › java › convert java objects to from json using gson
Convert Java objects to from JSON using Gson - Mkyong.com
May 6, 2024 - 7.3 The following example uses Gson to parse the above JSON string, get the data array, and convert it to a list of Person objects. GsonConvertJsonToObject4.java · package com.mkyong.json.gson; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import com.mkyong.json.model.Person; import java.lang.reflect.Type; import java.util.List; public class GsonConvertJsonToObject4 { public static void main(String[] args) { Gson gson = new Gson(); String json = """ { "company":"he