java无法从JSONArray获取JSONObject
我的php:
<?php
$con=mysqli_connect("localhost","xxx","xxx","xxx");
$result = mysqli_query($con, "SELECT username, x,y FROM user");
$jsonData = array();
while($array = mysqli_fetch_assoc($result)){
$jsonData[] = $array;
}
echo json_encode($jsonData);
mysqli_close($con);
?>
我将数据提取到JSONArray:[{"username":"one","x":"22.","y":"55"},{"username":"two","x":2,"y":5}]
Android代码:
//Connect to mysql.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http:example.com/fetchCoordinates.php");
//Getting response
HttpResponse response = httpClient.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
//Trying to get fetch from array.
JSONArray array = new JSONArray(responseBody);
JSONObject jsonObject = array.getJSONObject(0);
double x = jsonObject.getDouble("x");
Eror:
org.json.JSONArray cannot be converted to JSONObject
它不起作用。我受够了
# 1 楼答案
问题出在我的PHP代码中
出了什么问题:
什么是正确的:
为什么
# 2 楼答案
要从数组中创建json对象,数组必须是关联的,这样您就可以将代码更改为这个或那个
# 3 楼答案
JSON是有效的,但问题是它不包含JSONObject。它只是一个字符串数组。要真正从中获取JSONObject,它需要是一个实际JSONObject数组。尝试如下格式化数据:
请注意,包含在方括号
[]
中的数组包含逗号分隔的JSONObject,它们是包含在大括号{}
中的键值对你应该仔细阅读如何正确格式化JSON。这里有一个很好的资源:http://www.w3schools.com/json/default.asp
另请参见此答案以获取一些有用的信息: How do you represent a JSON array of strings?