【问题标题】:Get JSON string from Android JSONException从 Android JSONException 获取 JSON 字符串
【发布时间】:2016-03-12 16:26:51
【问题描述】:

我的 Volley 请求可以返回为 JSONArray(有效)或 JSONObject(错误消息),为了正确显示错误响应,我想将失败的 JSONArray 字符串解析为 JSONObject。似乎 JSONException 对象包装了原始文本。是否可以只获取失败的文本以进行不同的解析?

例子:

org.json.JSONException: Value {"error":"User has not signed up to be a customer"} of type org.json.JSONObject cannot be converted to JSONArray

我只想获取 JSON 字符串组件,因为它是一个有效的 JSONObject。

【问题讨论】:

  • 您的错误是与HTTP 200 一起出现的还是您获得了特定的状态码?

标签: android-volley jsonobject jsonexception


【解决方案1】:

因为你的响应要么是JSONArray(有效)要么是JSONObject(错误信息),所以可以参考以下代码:

// Check the response if it is JSONObject or JSONArray
Object json = new JSONTokener(response).nextValue();
if (json instanceof JSONObject) {
    // do something...
} else if (json instanceof JSONArray) {
    // do something...
}

希望对你有帮助!

【讨论】:

  • 这为我指明了正确的方向,谢谢!我添加了一个答案,看看我做了什么。
【解决方案2】:

我认为实际上不可能只从 JSONException 中检索 JSON 字符串,所以最后我从 BNK 那里得到了答案,并在这种情况下做了可能是最简单的解决方案。

诀窍似乎是接收一个 StringRequest 并在您知道有一个有效的字符串响应后进行 JSON 处理。这是我的项目中的样子。

StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            activity.hideProgress();

            try {
                Object json = new JSONTokener(response).nextValue();
                if (json instanceof JSONArray) {
                    // an array is a valid result
                    dataModel.loadData((JSONArray)json);
                } else if (json instanceof JSONObject) {
                    // this is an error
                    showErrorMessageIfFound((JSONObject)json);
                }
            } catch (JSONException error) {
                error.printStackTrace();
            }

            refreshTable();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            activity.hideProgress();
            showVolleyError(error);
            // check for a JSONObject parse error
        }
    });

首先有一个 StringRequest 来检索响应。错误响应使用我的自定义错误处理器显示错误。成功响应解析 JSON 并使用最终结果向最终用户显示正确的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 2022-09-24
    • 2012-12-12
    • 2020-11-10
    • 2016-09-30
    相关资源
    最近更新 更多