MattBlack MattBlack - 10 months ago 74
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?


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 Source

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) {

{} : 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.