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

[{"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",
        )
    ));
?>

subject键在JSONArray内部的JSONObject中,所以从jsonStr字符串中获取JSONArray:

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

相关内容

最新更新