-1

How to put arrayList in jsonArray on server side?

try to put parameter "list": [ { "year": "2019", "amt": 6222 }, { "year": "2016", "amt": 5555 } ]}

2 Answers2

1

Try this, it will work :

JSONObject jsonObject1 = new JSONObject();
JSONArray jsonArray = new JSONArray();

try {
    jsonObject1.put("year", "2019");
    jsonObject1.put("amt", "6222");
    jsonArray.put(jsonObject1);
    JSONObject jsonObject2 = new JSONObject();

    jsonObject2.put("year", "2016");
    jsonObject2.put("amt", "5555");
    jsonArray.put(jsonObject2);

    JSONObject jsonObjectList = new JSONObject();
    jsonObjectList.put("list",jsonArray);
} catch (JSONException e) {
    e.printStackTrace();
}

The result will be:

{"list":[{"year":"2019","amt":"6222"},{"year":"2016","amt":"5555"}]}
Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
0

Here is your problem solution, try this

  JSONArray jsonArray =  new JSONArray();
       for (int i =0; i < ItemModelList.size(); i++){
         JSONObject jsonObject = new JSONObject();
         jsonObject.put("year", String.valueOf(ItemModelList.get(i).getYear()));
         jsonObject.put("amt", String.valueOf(ItemModelList.get(i).getAmount()));
         jsonArray.put(jsonObject);
         requestJson.put("list", jsonArray);
       }

Result:
 "list": [ { "year": "2019", "amt": 6222 }, { "year": "2016", "amt": 5555 } ]
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – xiawi Nov 14 '19 at 15:46