0

我有其他人编写的 Json 解析器类。我闻到这种检查器方法不好:

    public boolean isCorrectResponse() {
    try {
        if (localResponse != null) {
            JSONObject jResponse = new JSONObject(localResponse);
            if (jResponse.get("result") instanceof JSONObject) { 
                JSONObject jResult = jResponse.getJSONObject("result");
                if (jResult.get("error") instanceof JSONArray) {
                    JSONObject jError = jResult.getJSONArray("error").getJSONObject(0);
                    if (!jError.toString().equals("")) {
                        String errorMsg = jError.getString("msg");
                        String errorCode = jError.getString("code");
                        showErrorMessage(errorCode + "; " + errorMsg);
                        return false;
                    }
                }
            }
        } else {
            return false;
        }
    } catch (JSONException e) {
        L.e("ERROR: on isCorrectResponse method!");
        e.printStackTrace();
        //return false; //Added myself Google Json should throw error shouldn't it??? Which means response was wrong???
    } 
    return true;
}

不应该在第一次尝试创建时抛出错误 JSONObject jResponse = new JSONObject(localResponse); 并且一切都会立即解决(我只需要返回false)?是否需要在 try 正文中进行这些额外检查?我正在使用 Google Gson 库来解析 Json 并为 Android 开发。

4

1 回答 1

1

解析 JSON 的每个标签是一项艰巨的工作,检查 if (jResponse.get("result") instanceof JSONObject) 不是一个好主意

更好的使用

 JSONObject result =jResponse.get("result") instanceof JSONObject)
 if (result == null) return false;

无论如何,如果您向 NullPointerException 添加捕获,则可以避免这种情况。当结果为空时,当您尝试解析下一个标签时,应用程序将抛出异​​常

于 2013-07-26T08:05:54.080 回答