try {
JSONArray jsonArray = new JSONArray(intent.getStringExtra("chatData"));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i);
messagesArr = new JSONArray(item.getString("message"));
messagesObj = new JSONObject();
messagesObj.put("messages", messagesArr);
populateMessages(messagesObj);
}
} catch (Exception e) {
}
我还尝试更改以下行但没有成功:
messagesArr = new JSONArray(item.getJSONObject("message"));
任何建议都表示赞赏。
item = {"message":"User has joined.","type":"agent","created":"2016-11-21 20:55:22","name":"Username"}
1-21 21:15:40.775 23532-23532/com.example.examplemobile W/System.err: org.json.JSONException: Value Johnny of type java.lang.String cannot be converted to JSONArray
11-21 21:15:40.775 23532-23532/com.example.examplemobile W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
11-21 21:15:40.785 23532-23532/com.example.examplemobile W/System.err: at org.json.JSONArray.<init>(JSONArray.java:96)
11-21 21:15:40.785 23532-23532/com.example.examplemobile W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
答案 0 :(得分:1)
您尝试将String
解析为JSONArray
,这就是它抛出异常的原因。要将其解析为JSONArray,您必须拥有以下数据:{ "message":["String1", "String2", "String3"] }
将您的messagesArr
变量更改为字符串,然后访问&#34;消息&#34;字符串调用messagesArr = item.getString("message");
答案 1 :(得分:1)
根据您在评论中提供的json字符串,它不是有效的json字符串
[{"type":"agent","message":"User has joined the chat.","created":"2016-11-21 21:40:31","name":"User"},{"type":"agent","message":"example message,"created":"2016-11-21 21:40:36","name":"User"},{"type":"agent","message":"User has left the chat.","created":null,"name":"User"}]
在example message
尝试将json字符串更改为
[
{
"type": "agent",
"message": "User has joined the chat.",
"created": "2016-11-21 21:40:31",
"name": "User"
},
{
"type": "agent",
"message": "example message",
"created": "2016-11-2121: 40: 36",
"name": "User"
},
{
"type": "agent",
"message": "Userhasleftthechat.",
"created": null,
"name": "User"
}
]
让我知道结果
答案 2 :(得分:0)
我认为您需要将String JSON intent.getStringExtra("chatData")
转换为JSON数组。
也许这个链接可以提供帮助 Convert String To JSON Array