1

I am doing a project in android. And I have a string with JSON format as follows:

"[
    {
    "id":46,
    "title":"Lorem ipsum dolor sit amet, consectetur adipiscing elit",
    "description":"Suspendisse lacinia dui ut metus ullamcorper,",
    "start_date":"October 26, 2015",
    "end_date":"January 1, 2016",
    "questions":
        [{
        "question":"<p>Proin aliquam augue eu ipsum viverra,<\\\/p>\\n",
        "options"frown emoticon"Yes","No"]
        },
        {
        "question":"<p>Morbi pharetra augue eu nunc porta<\\\/p>\\n",
        "options"frown emoticon"One","Two","Three","All"]
        },
        {
        "question":"<p>In nec dui pulvinar, ultrices <\\\/p>\\n",
        "options"frown emoticon"Yes","No","Other"]
        }]
    }
]"

Can any one help me to convert this string to JSONobject?

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
Sangharsha
  • 88
  • 11
  • 2
    That's not a JSONObject, it's a JSONArray.... JSONArray array = new JSONArray(yourString); – mjp66 Nov 20 '15 at 09:06
  • Possible duplicate of [How to parse JSON in Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – Selvin Nov 20 '15 at 09:36

5 Answers5

2

This is not JSONObject. Its an JSONArray.

You can get JSONArray like below.

JSONArray jsonArray = new JSONArray(responseString);

From array you can get JSONObject like below.

for(int i = 0 ; i< jsonArray.length() ; i++){

        // This will get first JSONObject from JSONArray.
        JSONObject jObject = jsonArray.getJSONObject(i);

        // Get all key from array using JSONObject.
        int id = jObject.getInt("id");
        String id = jObject.getString("title");
        String id = jObject.getString("description");
        String id = jObject.getString("start_date");
        String id = jObject.getString("end_date");

        // Get Inner question JSONArray
        JSONArray queArray = jObject.getJSONArray("questions");
        for(int j = 0 ; j< queArray.length() ; j++){
                String question = queArray.getJSONObject(j).getString("question");
                String options= queArray.getJSONObject(j).getString("options");
        }
}
Chirag Savsani
  • 6,020
  • 4
  • 38
  • 74
  • i tried your solution but it shows the following error: `org.json.JSONException: Value [{ of type java.lang.String cannot be converted to JSONArray` – Sangharsha Nov 20 '15 at 10:14
  • `org.json.JSONException: Value [{ of type java.lang.String cannot be converted to JSONArray` – Sangharsha Nov 20 '15 at 10:19
  • This Happens because your string has no valid json format. copy your string and past that string in this site . http://codebeautify.org/jsonviewer It will show error like Invalid Json array string. – Chirag Savsani Nov 20 '15 at 10:24
  • @Sangharsha First valid your string because your string is not valid json formate. once string is validate, my solution will always work. – Chirag Savsani Nov 20 '15 at 10:33
2

Your string cannot be converted to a JSONObject. You first need to convert it to a JSONArray:

JSONArray array = new JSONArray(yourString);

Once you have that, you can get your JSONObject from it:

JSONObject object = array.getJSONObject(0);

the value '0' is the position of the object you're accessing, in your case you only have one object in your array and we can just get to it by accessing the object at the '0' position (if you had more than one object here, then you'd access them all using a for() loop, as shown below).

Once you've gotten your JSONObject, you can now pick off whatever key/val pairs it contains. Example:

int myId = object.getInt("id");
String myTitle = object.getString("title");

If you want to get at the array of questions held in this object, you now again need to create a JSONArray from it:

JSONArray questionsArray = object.getJSONArray("questions");

In this case, we have more than one JSONObject in the array, so we create a for() loop to access everything in there:

for (int i = 0; i < questionsArray.length(); i++) {
    JSONObject questionObject = questionsArray.getObject(i);
    String myQuestion = questionObject.getString("question");
    String myOptions = questionObject.getString("options");
}

BTW your json string is invalid, specifically the "options" key/vals:

"options"frown emoticon"Yes","No"

Should be like this:

"options": "frown emoticon\"Yes\",\"No\""

UPDATE 1: your JSONException is probably being thrown due to a mangled json string. It should look like this:

[
    {
        "id": 46,
        "title": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
        "description": "Suspendisse lacinia dui ut metus ullamcorper,",
        "start_date": "October 26, 2015",
        "end_date": "January 1, 2016",
        "questions": [
            {
                "question": "<p>Proin aliquam augue eu ipsum viverra,<\\/p>\\n",
                "options": "frownemoticon\"Yes\",\"No\""
            },
            {
                "question": "<p>Morbipharetraaugueeununcporta<\\/p>\\n",
                "options": "frownemoticon\"One\",\"Two\",\"Three\",\"All\""
            },
            {
                "question": "<p>Innecduipulvinar,ultrices<\\/p>\\n",
                "options": "frownemoticon\"Yes\",\"No\",\"Other\""
            }
        ]
    }
]

UPDATE 2: in case you're reading from a fixed json string somewhere in your app, then the string should look like this (note that in this case, every quote mark has to be escaped with a backslash):

String yourString = "[{\"id\":46,\"title\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit\",\"description\":\"Suspendisse lacinia dui ut metus ullamcorper,\",\"start_date\":\"October 26, 2015\",\"end_date\":\"January 1, 2016\",\"questions\":[{\"question\":\"<p>Proin aliquam augue eu ipsum viverra,<\\\\/p>\\\\n\",\"options\":\"frownemoticon\\\"Yes\\\",\\\"No\\\"\"},{\"question\":\"<p>Morbipharetraaugueeununcporta<\\\\/p>\\\\n\",\"options\":\"frownemoticon\\\"One\\\",\\\"Two\\\",\\\"Three\\\",\\\"All\\\"\"},{\"question\":\"<p>Innecduipulvinar,ultrices<\\\\/p>\\\\n\",\"options\":\"frownemoticon\\\"Yes\\\",\\\"No\\\",\\\"Other\\\"\"}]}]";
mjp66
  • 4,214
  • 6
  • 26
  • 31
  • i tried your solution but it shows the following error: `org.json.JSONException: Value [{ of type java.lang.String cannot be converted to JSONArray` – Sangharsha Nov 20 '15 at 10:16
  • Double check your json string. I mentioned in my answer that it's not valid. I'll update my answer in a sec with a properly formatted string. – mjp66 Nov 20 '15 at 12:03
  • Thanks it Solved my problems.... The double code at the starting and the end of the string was the problems.... – Sangharsha Nov 20 '15 at 16:01
1
JSONArray jsonArray = new JSONArray(yourString);
JSONObject obj=jsonArray.getJsonObject(0);
AnswerDroid
  • 1,873
  • 2
  • 33
  • 52
1

As mentioned by others, this is a JSON array. However, if what you are going to do is parsing it, I'd recommend you to use GSON library, which handles parsing the whole JSON string to the Java classes that you need. You can use annotations to let the converter know which fields in your classes map to the corresponding JSON keys. It is really useful.

1

This work for me -

 String jsonString = "{ \"name\": \"Aditya\", \"java\": true }";
 JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class);
Aditya Nandardhane
  • 915
  • 1
  • 8
  • 22