有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

它不起作用。我受够了


共 (3) 个答案

  1. # 1 楼答案

    问题出在我的PHP代码中

    出了什么问题:

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

    什么是正确的:

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

    为什么

    First method (fetch_rows) gave me not JSONArray with JSONObjects inside, but instead I got JSONArray with JSONStrings inside.

    In java code I tried to receive JSONObject from JSONArray, but I was getting error, because there wasn't any objects(there were strings).

  2. # 2 楼答案

    要从数组中创建json对象,数组必须是关联的,这样您就可以将代码更改为这个或那个

      while($array = mysqli_fetch_assoc($result)){
           $jsonData[] = $array;
      }
    
  3. # 3 楼答案

    JSON是有效的,但问题是它不包含JSONObject。它只是一个字符串数组。要真正从中获取JSONObject,它需要是一个实际JSONObject数组。尝试如下格式化数据:

    [{
        "name": "one",
        "num1": "22",
        "num2": "55"
    }, 
    {
        "name": "two",
        "num1": "2",
        "num2": "5"
    }]
    

    请注意,包含在方括号[]中的数组包含逗号分隔的JSONObject,它们是包含在大括号{}中的键值对

    你应该仔细阅读如何正确格式化JSON。这里有一个很好的资源:http://www.w3schools.com/json/default.asp

    另请参见此答案以获取一些有用的信息: How do you represent a JSON array of strings?