Reputation: 61
I'm attempting to create a new JSONObject from a String however for some reason the new JSONObject is always null - and I'm unsure why.
Any suggestions are appreciated.
JSONObject messagesObj;
String mArr = intent.getStringExtra("msgArr");
try {
if (mArr != null)
messagesObj = new JSONObject(mArr);
if (messagesObj != null)
populateMessages(messagesObj);
DataManager.clientChatMarkMessagesSeen(chatId);
} catch (JSONException e) {
// DataManager.clientChatLoad(this);
e.printStackTrace();
}
String mArr = [{"message":"User has joined the chat.","type":"agent","created":"2016-12-07 17:35:09","name":"User"},{"message":"Hello World?","type":"agent","created":"2016-12-07 17:35:17","name":"User"},{"message":"User has left the chat.","type":"agent","created":"2016-12-07 17:38:40","name":"User"}]
Upvotes: 1
Views: 1269
Reputation: 183
Use JSONArray array = new JSONArray("string here"). It's an array if it starts with square brackets.
Upvotes: -1
Reputation: 4667
The string is json array not object..please see the root node it is not {}
Modify the string like this array of objects
String mArr = {"results": [{"message":"User has joined the chat.","type":"agent","created":"2016-12-07 17:35:09","name":"User"},{"message":"Hello World?","type":"agent","created":"2016-12-07 17:35:17","name":"User"},{"message":"User has left the chat.","type":"agent","created":"2016-12-07 17:38:40","name":"User"}]}
Upvotes: 0
Reputation: 93561
Because that isn't a json object- its a JSONArray. Try creating a JSONArray instead of a JSONObject
Upvotes: 4