1

我正在尝试将以下字符串作为 json 对象:

 [
    {
        "id": "picture1",
        "caption": "sample caption",
        "picname": "sample picture name"
      }
 ]

并将它变成一个数组,这样我就可以填充一个列表

我已经尝试通过这样做将它变成一个 jsonarray:

JSONArray myjsonarray = myjson.toJSONArray(string_containing_json_above); 

但这似乎不起作用。

===============

这是工作解决方案的完整代码

myjson = new JSONObject(temp);
String String_that_should_be_array = myjson.getString("piclist");
JSONArray myjsonarray = new JSONArray(String_that_should_be_array);
For(int i = 0; i < myjsonarray.length(); i++){
    JSONObject tempJSONobj = myjsonarray.getJSONObject(i);
    showToast(tempJSONobj.get("caption").toString());
}

temp 是来自服务器的 json

4

3 回答 3

4

问题在这里:

JSONArray myjsonarray = myjson.toJSONArray(temparray); 

解决方案:

JSONArray myjsonarray = new JSONArray(myJSON);   
// myJSON is String

现在在这里你有 JSONArray,迭代它并准备ArrayList你想要的任何类型。

于 2013-04-11T06:12:29.720 回答
3

在这里你得到 JSONArray 所以改变

JSONArray myjsonarray = myjson.toJSONArray(temparray); 

线如下图

JSONArray jsonArray = new JSONArray(readlocationFeed);

之后

 JSONArray jsonArray =  new JSONArray(readlocationFeed);

    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject explrObject = jsonArray.getJSONObject(i);
        explrObject.getString("caption");
}
于 2013-04-11T06:19:12.290 回答
0

JSONArray 不起作用,因为您提供的 JSON 不是数组。您可以在此处阅读有关 JSON 语法的更多信息:http: //www.w3schools.com/json/json_syntax.asp

同时,您可以通过一次将 JSON 解析为一个字符串来手动创建数组。

JSONObject strings = new JSONObject(jsonString);
String array[] = new String[5];

if (jsonString.has("id"){
    array[0] = jsonString.getString("id");
}
if (jsonString.has("caption"){
    array[1] = jsonString.getString("caption");
}
...

等等

于 2013-04-11T06:14:47.840 回答