安卓的JSONObject不能转换为JSONArray [英] Android: JSONObject cannot be converted to JSONArray

查看:783
本文介绍了安卓的JSONObject不能转换为JSONArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用JSON摆脱php文件数据到Android。这是我的code:

  ....
HttpEntity E = r.getEntity();
字符串数据= EntityUtils.toString(E);
JSONArray时间轴=新JSONArray(数据);
去年的JSONObject = timeline.getJSONObject(0);
最后返回;

当我调试程序有JSONException在这条线:

 的JSONObject最后= timeline.getJSONObject(0);

数据是 {一:1,B:2,C:3,D:4,E:5} 和唯一的例外是:

  org.json.JSONException:值{D:4,E:5,B:2,C:3,一:1}型的org.json.JSONObject不能转换到JSONArray


解决方案

的异常信息是相当明确的,一看 JSON语法图应该是说明问题。您code接收到的JSON字符串是:

  {一:1,B:2,C:3,D:4,E:5}

这串重新presents一个的对象的,而不是一个数组。阵列的一个例子是这样的:

  [1,2,3,4,5]

甚至是这样的:

  [{一:1,B:2,C:3,D:4,E:5}]

请注意,开始和结束括号

我想你会发现异常的位置有些误导。我不知道这是否是某种延迟初始化或者别的什么的结果,但我相信,原因居然是这一行:

  JSONArray时间表=新JSONArray(数据);

由于数据字符串重新presents一个JSON对象,而不是一个数组,这个操作显然是不可能的。

I want to get data from php file to Android using JSON. This is my code:

....
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;

When I debug the program there is JSONException on this line:

JSONObject last = timeline.getJSONObject(0);

Data is {"a":1,"b":2,"c":3,"d":4,"e":5} and the Exception is:

org.json.JSONException: Value {"d":4,"e":5,"b":2,"c":3,"a":1} of type org.json.JSONObject cannot be converted to JSONArray

解决方案

The exception message is quite explicit and a look at the JSON syntax diagrams should be illustrative. The JSON string that your code received is:

{"a":1,"b":2,"c":3,"d":4,"e":5}

This string represents an object, not an array. An example of an array would be this:

[1, 2, 3, 4, 5]

or even this:

[{"a":1,"b":2,"c":3,"d":4,"e":5}]

Note that starting and closing brackets.

I think that you will find that the exception location is slightly misleading. I don't know if it is a result of some sort of lazy initialization or something else, but I believe that the cause is actually this line:

JSONArray timeline = new JSONArray(data);

Since the data string represents a JSON object and not an array, this operation is clearly impossible.

这篇关于安卓的JSONObject不能转换为JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆