简体   繁体   中英

Convert json formatted string into jsonObject Android

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 ?

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

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\\\"\"}]}]";
JSONArray jsonArray = new JSONArray(yourString);
JSONObject obj=jsonArray.getJsonObject(0);

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.

This work for me -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM