在php中创建JSONArray并将其发送到android

时间:2014-07-14 06:48:49

标签: java php android json

我正在开发一个Android项目,我需要在我的php服务器中创建一个JSON消息并将其发送到Android设备。

我在php中编写了以下代码

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

但结果就像

 {
    "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
        }
    }
}

并且它不是json数组,我在我的android代码中得到异常,这只是

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

出了什么问题?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

{表示对象,[表示数组。

在你的情况下它是两个对象。

JSONObject jObject = new JSONObject(res);

是正确的,包含另一个名为event_array的对象。

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

而jsonEvents现在持有

jsonEvents.getString("id_1");

这是另一个jsonObject。

如果要输出为数组,请再次使用数组。

正如http://de3.php.net/json_encode中所写,得到一个数组

一定是这样的
echo json_encode(array(array('event_array' => $event_array)));

所以这意味着它应该像你的情况一样。

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

用Java阅读它更可能

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

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