-4

I have to create JSON response like the below one.

    [{"Name":"Shampoo","Qty":"3","Amt":"300"},
    {"Name":"Soap","Qty":"1","Amt":"50"}]

Code:

    ArrayList<String> al= new ArrayList<String>();
    al.addAll(name);
    al.addAll(qty);
    al.addAll(price);

    Gson gson = new Gson();
    String json = gson.toJson( al );

    System.out.println(json);
    JSONObject pa = new JSONObject();
    childData = new JSONObject();

    try {
        childData.put("Name", name);
        childData.put("Qty", qty);
        childData.put("Amt", price);
        pa.put("Detais",childData);

    } catch (JSONException e) {
        e.printStackTrace();
    }

But the above code creates the response like this

      {"Name":"[Shampoo, Soap]","Qty":"[3, 1]","Amt":"[300, 50]"}
Anushya
  • 3
  • 3

1 Answers1

0

From the al.addAll() calls I deduce name, qty, and price are lists. So you are handing lists to the childData.put() calls. This produces the output you found, and array of values at each JSON key (child element) containing all elements in the list handed to that childData.put() call.

If you want your first JSON you should loop over all elements in you list and add (put) them one by one on a parent element that resembles your (name, qty, price) pair. E.g.

JSONArray jA  = new JSONArray()
for(int j=0; j<condition;j++){
    JSONObject pa = new JSONObject();
    for(int i=0; i<name.length;i++) {
        childData = new JSONObject();
        childData.put("Name", name[i]);
        childData.put("Qty", qty[i]);
        childData.put("Amt", price[i]);
        pa.put("Detais",childData);
    }
    jA.put(pa);
}
bastijn
  • 5,841
  • 5
  • 27
  • 43
  • childData= {"Name":"Shampoo","Qty":"2","Amt":"300"} pa= [{"Name":"Shampoo","Qty":"2","Amt":"300"}] childData= {"Name":"Soap","Qty":"3","Amt":"210"} pa= [{"Name":"Soap","Qty":"3","Amt":"210"}, {"Name":"Soap","Qty":"3","Amt":"210"}]. In pa JSONArray last childData value is getting stored – Anushya Apr 10 '17 at 06:44
  • Well you have to loop creation of parents as well in an outer loop of course and add to an json array. – bastijn Apr 10 '17 at 15:12