JSONObject.toString()将内部JSONArray转换为Android中的字符串

时间:2017-02-17 06:54:48

标签: android json

我正在创建一个JSON请求,如下所示:

JSONObject request = new JSONObject();
request.put("ID", "35");
    request.put("password", "password");
    List<JSONObject> fieldList = new ArrayList<>();
    for (int i = 0; i < 3; i++) {
        fieldList.add(new JSONObject()
                 .put("unitid", "unitid " + i)
                 .put("price", "Price " + i));
    }

request.put("unitsummary", new JSONObject()
       .put("unitsummarydetail", fieldList)
);

String requestString = request.toString();

requestString变量的值应为:

{
  "ID": "35",
  "password": "password",
  "unitsummary": {
    "unitsummarydetail": [
      {
        "price": "Price 0",
        "unitid": "unitid 0"
      },
      {
        "price": "Price 1",
        "unitid": "unitid 1"
      },
      {
        "price": "Price 2",
        "unitid": "unitid 2"
      }
    ]
  }
}

但它是:

{
  "ID": "35",
  "password": "password",
  "unitsummary": {
    "unitsummarydetail": "[{\"unitid\":\"unitid 0\",\"price\":\"Price 0\"}, {\"unitid\":\"unitid 1\",\"price\":\"Price 1\"}, {\"unitid\":\"unitid 2\",\"price\":\"Price 2\"}]"
  }
}

它将unitsummarydetail转换为字符串。 我已经尝试但没有在互联网上找到类似的问题或任何解决方案。 我的代码中是否有任何问题,或者这是库的行为?

欢迎提出任何想法或解决方案代码段。

感谢。

3 个答案:

答案 0 :(得分:2)

更改您的代码

request.put("unitsummary", new JSONObject()
   .put("unitsummarydetail", fieldList));

request.put("unitsummary", new JSONObject()
   .put("unitsummarydetail", new JSONArray(fieldList)));

答案 1 :(得分:2)

使用JSONArray而不是ArrayList。

JSONObject request = new JSONObject();
request.put("ID", "35");
request.put("password", "password");
JSONArray fieldList = new JSONArray();
for (int i = 0; i < 3; i++) {
fieldList.put(new JSONObject() .put("unitid", "unitid " + i)      .put("price", "Price " + i));
}
request.put("unitsummary", new JSONObject() .put("unitsummarydetail",   fieldList) );
String requestString = request.toString();

输出:

  

{ “ID”: “35”, “密码”: “密码”, “unitsummary”:{ “unitsummarydetail”:[{ “的UnitID”:“的UnitID   0“,”price“:”价格0“},{”unitid“:”unitid 1“,”price“:”Price   1“},{”unitid“:”unitid 2“,”price“:”Price 2“}}}}

答案 2 :(得分:0)

你可以创建一个JSON数组unitummarydetail并在for循环中添加所有json对象unitummary