在 Android 的另一个 JSON 对象下添加一个 JSON 对象

Adding a JSON Object under another JSON Object for Android

我想创建这样的 JSON 结构:

{
"request": {
"slice": [
  {
    "origin": "BLR",
    "destination": "CCU",
    "date": "2015-06-18"
  }
],
"passengers": {
  "adultCount": 1,
  "infantInLapCount": 0,
  "infantInSeatCount": 0,
  "childCount": 0,
  "seniorCount": 0
},
"solutions": 20,
"refundable": false
}
}

为此我编写了以下代码行:

    JSONObject request_hdr = new JSONObject();
    JSONObject request = new JSONObject();
    JSONArray slice = new JSONArray();
    JSONObject data = new JSONObject();

    data.put("origin",Origin);
    data.put("destination",Destination);
    data.put("date", Start_Date);
    slice.put(data);
    request.put("slice",slice);
    request_hdr.put("request",request);

    JSONObject addl_info = new JSONObject();
    addl_info.put("adultCount",Num_Adult);
    addl_info.put("infantInLapCount",Num_Infant);
    addl_info.put("infantInSeatCount", 0);
    addl_info.put("childCount",0);
    addl_info.put("seniorCount",0);
    request.put("passengers",addl_info);
    request_hdr.put("request",request);

    JSONObject solutions = new JSONObject();
    solutions.put("solutions", 20);

    JSONObject refundable = new JSONObject();
    refundable.put("refundable","false");

我无法将 JSON 对象 'solutions' 和 'refundable' 添加到根对象 'request'。

有人可以帮我解决这个问题吗?我也不确定(即从未测试过解析 JSON 返回)上面写的代码是否正常工作。

任何help/suggestion将不胜感激。提前致谢!

如果您的代码到此结束,

JSONObject solutions = new JSONObject();
solutions.put("solutions", 20);

JSONObject refundable = new JSONObject();
refundable.put("refundable","false");

那么问题是您实际上从未将对象添加到您的 request 对象中。

此外,这些是值而不是 JSONObjects,因此您应该将其替换为:

requests.put("solutions", 20);
requests.put("refundable", false);

如果您希望它与您原来的结构匹配 post。