gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:40:01 25 4
gpt4 key购买 nike

我正在创建一个 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 转换为字符串。我试过但没有在互联网上找到类似的问题或任何解决方案。我的代码有什么问题还是库的行为?

欢迎任何想法或解决方案代码 fragment 。

谢谢。

最佳答案

使用 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","password":"password","unitsummary":{"unitsummarydetail":[{"unitid":"unitid 0","price":"Price 0"},{"unitid":"unitid 1","price":"Price 1"},{"unitid":"unitid 2","price":"Price 2"}]}}

关于android - JSONObject.toString() 将内部 JSONArray 转换为 Android 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42291281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com