无法从JSONArray获取JSONObject [关闭]

My 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);
?>

My Fetched data to JSONArray: [{"username":"one","x":"22.","y":"55"},{"username":"two","x":2,"y":5}]

Android code:

        //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

It doesn't work. I'm stuck with it.

To create a json object from an array, the array has to be associative so you can change your code to this to archieve that.

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

Your JSON is valid, but your issue is that it does not contain a JSONObject. It's just an array of arrays of strings. To actually get JSONObjects out of it, it needs to be an array of actual JSONObjects. Try formatting your data something like this:

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

Notice that the array, which is contained within brackets [] contains comma separated JSONObjects, which are key-value pairs contained within curly braces {}.

You should read up on how to properly format JSON. Here is a good resource: http://www.w3schools.com/json/default.asp

Also see this answer for some helpful info: How do you represent a JSON array of strings?

The problem was in my PHP code.

What was wrong:

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

What is correct:

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

Why?

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).