java 使用 JSONTokener 将字符串解析为 JSONObject 或 JSONArray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15718919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:38:00  来源:igfitidea点击:

Parsing String with JSONTokener to JSONObject OR JSONArray

javajsonparsingrest

提问by Tobias

I'm using the following code to handle REST responses from my server:

我正在使用以下代码来处理来自我的服务器的 REST 响应:

if (response.getEntity() != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        StringBuilder builder = new StringBuilder();
        for (String line = null; (line = reader.readLine()) != null;) {
            builder.append(line).append("\n");
        }           
        JSONTokener tokener = new JSONTokener(builder.toString());
        try {
            rr.jsonObject = new JSONObject(tokener);                
        } catch (JSONException e) {             
            e.printStackTrace();

            Log.d("parsing", "creating json array");
            try {
                rr.jsonArray = new JSONArray(tokener);
            } catch (JSONException e1) {                    
                e1.printStackTrace();
            }

        }
    }

If the response is an JSONObject, it works perfectly but if the server returns a JSONArray, the second try block also throws although it's correct json.

如果响应是一个 JSONObject,它可以完美运行,但如果服务器返回一个 JSONArray,第二个 try 块也会抛出,尽管它是正确的 json。

03-30 14:09:15.069: W/System.err(6713): org.json.JSONException: End of input at character 314 of [{"__className":"stdClass","char3code":"DEU","fips_name":"Germany","alternate_names":"Germany, Deutschland, Allemagne, Alemania"},{"__className":"stdClass","char3code":"USA","fips_name":"United States","alternate_names":"United States of America, Vereinigte Staaten von Amerika, \u00c9tats-Unis, Estados Unidos"}]

回答by Stephen C

I expect the reason that this is failing is that when you call new JSONArray(tokener)the tokeneris no longer positioned at the start of the token stream. Try creating a new JSONTokenerinstance for the 2nd attempt at parsing..

我期望,这是失败的原因是,当你调用new JSONArray(tokener)tokener不再位于令牌流的开始。尝试JSONTokener为第二次解析尝试创建一个新实例..