Java:通过嵌套的JSON对象循环

时间:2013-12-03 09:43:02

标签: java json

我有以下存储消息的结构:

{
    "Channel_12": [
        ["[{\"to\":\"Bill\",\"msg\":\"Hello\",\"time\":\"10:36\"}]"], "[{\"agentName\":\"demo\",\"msg\":\"Hello 2\",\"time\":\"10:37\"}]"
    ],
    "Channel_34": [
        ["[{\"to\":\"Bill\",\"msg\":\"Hey 1\",\"time\":\"10:37\"}]"], "[{\"agentName\":\"demo\",\"msg\":\"Hey 2\",\"time\":\"10:38\"}]"
    ] }

我现在正在尝试遍历并获取给定频道的每条消息,假设我想要获取频道Channel_12的所有消息。

目前我有以下代码:

        org.codehaus.jettison.json.JSONArray c = obj.getJSONArray("Channel_12");

        for (int i = 0 ; i < c.length(); i++) {
            JSONObject obj = c.getJSONObject(i); <!-- Exception is here

            System.out.println(obj.getString("to").toString());
            System.out.println(obj.getString("msg").toString());

        }

但是我得到以下例外:

org.codehaus.jettison.json.JSONException: JSONArray[0] is not a JSONObject.
    at org.codehaus.jettison.json.JSONArray.getJSONObject(JSONArray.java:277)
    at im.Client$HistoryJSON.getHistory(Client.java:7229)
    at im.Client$32$4.run(Client.java:2246)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:715)
    at java.awt.EventQueue.access$400(EventQueue.java:82)
    at java.awt.EventQueue$2.run(EventQueue.java:676)
    at java.awt.EventQueue$2.run(EventQueue.java:674)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:86)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:685)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

更改您的代码,

        JSONArray c = jsonObject.getJSONArray("Channel_12");  //Change your code from here
        JSONArray array = c.getJSONArray(0);
        String data = c.getString(1);
        Log.i("#Values", array.getString(0) + "\t" + data);

查看我的结果,

enter image description here

答案 1 :(得分:0)

您的JSONArray似乎包含JSONArrayJSONObjectJSONArray a JSONObject

您是否掌控了源格式?因为它看起来有点奇怪。

结构如下: 在位置0是具有一个对象的数组,并且位置1是对象。

您的代码可以更改为:

org.codehaus.jettison.json.JSONArray c = obj.getJSONArray("Channel_12");
JSONArray array = c.getJSONArray(0);
JSONObject obj2 = array.getJSONObject(0);

System.out.println(obj2.getString("to").toString());
System.out.println(obj2.getString("msg").toString());