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\\\"\"}]}]";