MattBlack MattBlack - 14 days ago 7
Android Question

Java Json object error

I am using the code below to parse a json object but it keeps returning that the object is malformed. Is the issue that there something wrong with my json string?


{"members":[{"id":"1","firstname":"Matt","lastname":"Black","email":"matt*****@gmail.com","smartcode":"1"}]}


String json = response;
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
String firstnameJ = obj.getString("firstname");
Log.i("FIRSTNAME", firstnameJ);
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}

Answer

you can try this.

    try {
        JSONObject jsonObject = new JSONObject(js);
        JSONArray jsonMembers = jsonObject.getJSONArray("members");
        JSONObject jsonMember = jsonMembers.getJSONObject(0);
        String firstName = jsonMember.getString("firstname");
        Log.d(TAG,"biu biu first name --->" + firstName);
    } catch (JSONException e) {
        e.printStackTrace();
    }

{} : means JSONObject   [] : means JSONArray

So if you want to get right data, you need to use right Object.

Just read JSON's syntax,and you will find it's pretty easy to use.