DolDurma
DolDurma

Reputation: 17360

Android parse json get org.json.JSONException error

    String jsonStr = HelperInputStream.convertInputStreamToString(inputStream);
    if (jsonStr == null) {
        return;
    }
    String code,message = "";
    try {
        JSONObject object = new JSONObject(jsonStr);
        Log.e("code:" , object.getString("subject"));

jsonStr result is:

[{"code":"1","subject":"you have new message"}]

unfortunately i get this error is catch:

org.json.JSONException: Value [{"subject":"you have new message","code":"1"}] of type org.json.JSONArray cannot be converted to JSONObject

whats my code problem. in server i have only this code:

<?php
    echo json_encode(array(
        array(
            'code'=>'1',
            'subject'=>"you have new message",
        )
    ));
?>

Upvotes: 0

Views: 230

Answers (1)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

subject key is in JSONObject which is inside JSONArray so get JSONArray from jsonStr string:

JSONArray arrJSON = new JSONArray(jsonStr);
JSONObject object=arrJSON.getJSONObject(0);
Log.e("code:" , object.getString("subject"));

Upvotes: 2

Related Questions