0

我有一个从名为 data 的 HttpClient 返回的字符串。

Data = {"result":[{"id":"2","contextID":"1","name":"Kitchen","image":"81"},
{"id":"1","contextID":"1","name":"Living Room","image":"18"},
{"id":"3","contextID":"1","name":"Toilet","image":"75"}]}

然后我正在执行此代码:

resultArray = new JSONArray (data);

并返回这个 JSONArray。但是,我收到 JSONException 错误:

JSONObject cannot be converted to JSONArray

这肯定是 JSONArray 而不是 JSONObject?或者它是 JSONObjects 的 JSONObject?我对 JSON 很陌生,我想循环使用这些导入的值创建新的位置。有没有一种简单或成熟的方法来做到这一点?

非常感谢。

4

3 回答 3

2

Data是一个 JSONObject,并且Data["result"]是一个包含 JSONObjects 的 JSONArray。

于 2013-02-15T21:00:29.600 回答
1

它是一个 json 对象,其中包含 JSONObjects 的 JSONArray。{ } 表示对象,[] 表示数组。因此,您将顶级字符串作为 JSON 对象获取,然后将结果参数作为数组获取,然后将结果中的每个索引作为对象获取(您可以通过 getString 等获取这些参数的参数)。

于 2013-02-15T21:00:31.293 回答
0

Data is actually a JSONObject that contains a JSONArray named "result." If you wanted to get the JSONArray you'd have to do the following:

JSONObject dataObj = new JSONObject(data);
JSONArray dataArr = dataObj.getJSONArray("result");

For future reference, since you're new to JSON, data inside {} braces is a JSONObject and data inside [] braces is a JSONArray. Arrays and objects can be nested inside of each other and it's sometimes hard to read. I recommend formatting your data if you need help reading it. I personally use http://jsonformatter.curiousconcept.com/ to format and validate my data. I'm not associated with the site in any way. I just find it really useful.

于 2013-02-15T21:14:21.380 回答