Benas.M Benas.M - 7 months ago 20
PHP Question

Can't get JSONObject from JSONArray

I can't parse JSONArray to JSONObject. My goal is to Get JSONobjects from JSONArray, and then to get data from these JSONObjects.

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. Any help would be appreciated!!

Answer

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?