Benas.M Benas.M - 2 years ago 89
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:



$result = mysqli_query($con, "SELECT username, x,y FROM user");

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

echo json_encode($jsonData);


My Fetched data to JSONArray:

Android code:

//Connect to mysql.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("");

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

It doesn't work. I'm stuck with it. Any help would be appreciated!!

Answer Source

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:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download