简体   繁体   English

Android:JSONObject无法转换为JSONArray

[英]Android: JSONObject cannot be converted to JSONArray

I want to get data from php file to Android using JSON. 我想使用JSON将数据从php文件获取到Android。 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: 当我调试程序时,在此行上有JSONException:

JSONObject last = timeline.getJSONObject(0);

Data is {"a":1,"b":2,"c":3,"d":4,"e":5} and the Exception is: 数据为{"a":1,"b":2,"c":3,"d":4,"e":5} ,并且异常为:

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. 异常消息非常明确,对JSON语法图的查看应该是说明性的。 The JSON string that your code received is: 您的代码收到的JSON字符串是:

{"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. 由于data字符串表示一个JSON对象而不是一个数组,因此此操作显然是不可能的。

In Json arrays are described using [] . 在Json中,数组是使用[]来描述的。 There you define an object with five attributes. 在此定义具有五个属性的对象。

JSONArray timeline = new JSONArray(data);
// change JSONArray to JSONObject

JSONObject timeline = new JSONObject(data);// Like This

Your JSON data is not an array. 您的JSON数据不是数组。

Your json response is in Object form, not in Array form.So you have to simply parse your json object. 您的json响应是Object形式的,而不是Array形式的,因此您只需要简单地解析json对象即可。 Suppose "data" is the JSONObject tag in response. 假设“ data”是响应中的JSONObject标签。 Following is the way of Parsing: 以下是解析方式:

           HttpEntity e = r.getEntity();
           String result = EntityUtils.toString(e);
           JSONObject response=new JSOBObject(result);
           JSONOBject Data=response.getJSONObject("data");
           int a=Data.getInt("a");
           int b=Data.getInt("b");
           int c=Data.getInt("c");
           int d=Data.getInt("d");
           int e=Data.getInt("e");

Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM