【问题标题】:Android parse json get org.json.JSONException errorAndroid解析json得到org.json.JSONException错误
【发布时间】:2015-02-13 19:48:05
【问题描述】:
    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",
        )
    ));
?>

【问题讨论】:

    标签: android json android-json


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢先生,为什么我不能用switch 代替String code = i.getStringExtra("code"); 我喜欢用switch 而不是if,我得到这个错误:Error:(145, 24) java: strings in switch are not supported in -source 1.6 (use -source 7 or higher to enable strings in switch)
    猜你喜欢
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多