Android解析json get org.json.JSONException错误

时间:2015-02-13 19:48:06

标签: android json android-json

    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结果是:

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

不幸的是我得到的错误是catch

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

我的代码问题是什么。在服务器中我只有这个代码:

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

1 个答案:

答案 0 :(得分:2)

subject键位于JSONObject中,它位于JSONArray中,因此从jsonStr字符串获取JSONArray:

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