Droidthusiast
Droidthusiast

Reputation: 61

Creating new JSONObject from String Returns Null - JAVA / Android

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.

Source:

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();
            }

Values:

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

Answers (3)

Ayush Baheti
Ayush Baheti

Reputation: 183

Use JSONArray array = new JSONArray("string here"). It's an array if it starts with square brackets.

Upvotes: -1

Jayakrishnan
Jayakrishnan

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

Gabe Sechan
Gabe Sechan

Reputation: 93561

Because that isn't a json object- its a JSONArray. Try creating a JSONArray instead of a JSONObject

Upvotes: 4

Related Questions