strings95
strings95

Reputation: 681

create JSONArray in php and send it to android

i'm developing an android project which i need to create a JSON message in my php server and send it to the android devices.

i wrote the following code in php

$event_array = array();
// fill the event_array with some data
print json_encode(array('event_array' => $event_array));

but the result is like

 {
    "event_array": {
        "id_1": {
            "name": "name",
            "logo_address": "logo_address",
            "title": "title",
            "time": null,
            "address": null,
            "address_location": null,
            "explain": null,
            "type": null,
            "id": "id_1",
            "number_of_users": null
        },
        "id_2": {
            "name": "name2",
            "logo_address": null,
            "title": null,
            "time": null,
            "address": null,
            "address_location": null,
            "explain": null,
            "type": null,
            "id": "id_2",
            "number_of_users": null
        }
    }
}

and it's not a json array and i get exception in my android code which simply is

JSONObject jObject = new JSONObject(res);
JSONArray jArray = jObject.getJSONArray("event_array");

what's wrong?

thanks for any help

Upvotes: 0

Views: 512

Answers (1)

Emanuel
Emanuel

Reputation: 8106

{ means object, [ means array.

In your case its two objects.

JSONObject jObject = new JSONObject(res);

is correct and contains another object called event_array.

JSONObject jsonEvents = new JSONObject(jObject.getString("event_array"));

while jsonEvents now holds

jsonEvents.getString("id_1");

which is another jsonObject.

If you want to output as array, use array again.

As written in http://de3.php.net/json_encode it must be something like this to get an array

echo json_encode(array(array('event_array' => $event_array)));

So it means it should be like this to match your case.

 echo json_encode(
    array(
        'event_array' =>
        array(
            array("id_1" => array('name' => 'name', 'logo_...' => '...')),
            array("id_2" => array('name' => '....', 'logo_....' => '....'))
        )
 ));

to read this in Java its more likely

 JSONObject json = new JSONObject(data);
 JSONArray jsonArr = json.getString('event_array');

 for (int i = 0; i <= jsonArr.length(); i++) {
    JSONObject jsonEventData = jsonArr.getJsonObject(i);
 }

Upvotes: 1

Related Questions