Reputation: 61
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) {
}
I've also attempted changing the following line with no success:
messagesArr = new JSONArray(item.getJSONObject("message"));
Any suggestions are appreciated.
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)
Upvotes: 0
Views: 153
Reputation: 3043
From your json string that you provided on your comment, it is not a valid json string
[{"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"}]
It needs a double quotation mark after example message
Try to change the json string to
[
{
"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"
}
]
and let me know the result
Upvotes: 1
Reputation: 8909
You're trying to parse a String
as a JSONArray
, that's why it's throwing the exception. In order to parse it as a JSONArray, you'd have to have data like this: { "message":["String1", "String2", "String3"] }
Change your messagesArr
variable to a String, and then access the "message" string by calling messagesArr = item.getString("message");
Upvotes: 1
Reputation: 75
I think you need to convert your String JSON intent.getStringExtra("chatData")
to JSON Array.
Maybe this link can help Convert String To JSON Array
Upvotes: 0