gpt4 book ai didi

安卓 : JSONArray[0] is not a JSONObject

转载 作者:行者123 更新时间:2023-11-30 03:42:53 31 4
gpt4 key购买 nike

我在 Android 中有一个项目,我这里有这个 JSON,我需要解析它以便我可以使用数据:(我已经尝试在 JSONLint.com 上验证我的 JSON,一切正常)

{
"traces": [
"{\"lat\": \"42.842097\", \"lng\": \"-31.258422\", \"idTrace\": \"444e8079\"}",
"{\"lat\": \"56.842097\", \"lng\": \"-73.258422\", \"idTrace\": \"088b591a\"}"
]
}

问题是,当我尝试获取 JSONArray 中的 2 个 JSONObject 时,我总是遇到错误。

这是我的代码 fragment :

     (...)

StringBuilder builder = new StringBuilder();

for (String line = null; (line = reader.readLine()) != null;)
{
builder.append(line).append("\n");
}


JSONObject result = new JSONObject(builder.toString());
JSONArray list = result.getJSONArray("traces");


try{
for (int i = 0; i < list.length(); i++)
{ //this is where I get the error "JSONArray[0] is not a JSONObject"
JSONObject jsonObject = list.optJSONObject(i);


//String id = jsonObject.getString("idTrace");
//String lat = jsonObject.getString("lat");
//String lng = jsonObject.getString("lng");

(...)
}
(...)

我进行了大量搜索以找出问题所在,但人们似乎在做与我完全相同的事情...我找不到它不起作用的原因!

感谢您的帮助!

最佳答案

此 JSON 是否从您控制的 API 返回?我认为破坏的是 JSONArray 中项目周围的引号 - JSON 应如下所示:

{"traces": [
{"lat": "42.842097", "lng": "-31.258422", "idTrace": "444e8079"},
{"lat": "56.842097", "lng": "-73.258422", "idTrace": "088b591a"}
]}

请注意,每个 JSONObject 都没有引号。你现在拥有的更像是一个字符串数组......

关于安卓 : JSONArray[0] is not a JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15464727/

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