gpt4 book ai didi

java - 无法从 JSONArray 获取 JSONObject

转载 作者:行者123 更新时间:2023-11-29 21:02:37 25 4
gpt4 key购买 nike

我的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");

错误:

org.json.JSONArray cannot be converted to JSONObject

这不起作用。我被困住了。

最佳答案

要从数组创建 json 对象,该数组必须是关联的,以便您可以将代码更改为此来实现它。

  while($array = mysqli_fetch_assoc($result)){
$jsonData[] = $array;
}

关于java - 无法从 JSONArray 获取 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37081154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com