2014-07-14 06:48
浏览 20


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


    which is another jsonObject.

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

    As written in 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(
            'event_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);
    解决 无用
    打赏 举报

相关推荐 更多相似问题