-2
String orderdata="[
        {productid: 1, count: 2},
        {productid: 7, count: 7},
        {productid: 81, count 2}    
    ]"
String userId=2;
String slotdatetime=21/11/2015 5:00 PM
String address=204, Phase IV, Gurgaon
String total=2300;

This data i have available i have to make Json Format data like this

{
    userId: "2",
    slotdatetime: "21/11/2015 5:00 PM",  
    address: "204, Phase IV, Gurgaon",
    total: "2300",
    orderdata: [
        {productid: 1, count: 2},
        {productid: 7, count: 7},
        {productid: 81, count 2}    
    ]
}

But there is Problem to create Single String in which i have get given data like this please help me .

Mhanaz Syed
  • 229
  • 1
  • 5
  • 18

2 Answers2

0
    JSONObject json = new JSONObject();
    json.put("userId", "2");
    json.put("slotdatetime", "21/11/2015 5:00 PM");
    json.put("address", "204, Phase IV, Gurgaon");
    json.put("total",2300);

JSONObject jsonorderdata = new JSONObject();
jsonorderdata.put("productid", "1");
jsonorderdata.put("count", "2");

JSONArray ja = new JSONArray();
ja.put(jsonorderdata);

json.put("orderdata", ja);
Chris
  • 1,311
  • 2
  • 15
  • 37
0

This will produce what you want:

JSONObject object = new JSONObject();
try {
    object.put("userId", userId);
    object.put("slotdatetime", slotdatetime);
    object.put("total", total);
    object.put("orderdata", new JSONArray(orderdata));
} catch (JSONException e) {
    e.printStackTrace();
    // handle exception
}

A couple notes before trying the above and reporting that it doesn't work:

  1. your String orderdata can not be converted into a JSONArray as I've done above (new JSONArray(orderdata)) until you construct it so that it's actually valid.

  2. String userId and String total would be better off as ints.

mjp66
  • 4,214
  • 6
  • 26
  • 31