gpt4 book ai didi

Java:遍历嵌套的 JSON 对象

转载 作者:行者123 更新时间:2023-11-30 11:25:15 25 4
gpt4 key购买 nike

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

{
"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 的每条消息,假设我想获取 channel 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)

有什么想法吗?

最佳答案

更改您的代码,例如,

        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

关于Java:遍历嵌套的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20347577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com