doulao1934 2014-07-14 06:48
浏览 20
已采纳

在php中创建JSONArray并将其发送到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

  • 写回答

1条回答 默认 最新

  • doukuibi9631 2014-07-14 06:56
    关注

    { 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);
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?