简体   繁体   中英

How to parse json response in android which is of the following format

I am trying to parse a json response in android for my android application. I am getting org.json.JSONException . The response is as shown below:

 {
    id: "12345"
    email:"abc@gmail.com"
firstName:"abcd"
lastName:"efgh"
userName:"abc123"
    }

I am trying to parse the response as shown below:

 if (response != null) {
                    try {
                        //JSONObject jsonObj = new JSONObject(text);

                        // Getting JSON Array node
                       JSONArray contacts = new JSONArray(response.toString());

                        // looping through All Contacts
                        for (int i = 0; i < contacts.length(); i++) {
                            JSONObject c = contacts.getJSONObject(i);

                             id = c.getString("_id");
                             email = c.getString("email");
                             firstName = c.getString("firstName");
                             lastName = c.getString("lastName");
                             userName = c.getString("userName");
 }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

Can any one let me know what mistake am I doing in parsing the response. All suggestions are welcome.

Simply replace this you are using "_id" instead of "id"

id = c.getString("id");
email = c.getString("email");
firstName = c.getString("firstName");
lastName = c.getString("lastName");
userName = c.getString("userName");

Change this id = c.getString("_id"); to id = c.getString("id");

in the future, you may show error in logcat when parsing like this:

    catch (JSONException e) {
        e.printStackTrace();
        Log.e("TAG", e.getMessage());
    }

There are two things I can think of , first of all you should get to know that what are [] , {} . The square brackets are arrays in json and curly demonstrate the object , so I think you are casting it wrong

1>

JSONArray contacts = new JSONArray(response.toString()); "this is culprit"

You should change it to

JSONObject. Use JSONObject in place of JSONArray

and Secondly

2> change this key id = c.getString("_id");to

id = c.getString("id");

Make sure You are getting and writing spellings of all keys right else it would generate exception.

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