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

标签: json Android
发布时间: 2017/3/4 5:43:47
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我创建一个 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 作为字符串。 我试过,但没有找到类似的问题或任何解决方案上互联网。 我的代码中是否有任何问题或这是图书馆的行为?

任何想法或解决方案代码段都是欢迎的。

谢谢你。

解决方法 1:

使用 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","价格":"价格 0"},{"unitid":"unitid 1","价格":"价格 1"},{"unitid":"unitid 2","价格":"价格 2"}]}}

赞助商