简体   繁体   English

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

[英]Parsing String with JSONTokener to JSONObject OR JSONArray

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"}]

I expect the reason that this is failing is that when you call new JSONArray(tokener) the tokener is no longer positioned at the start of the token stream. 我希望失败的原因是,当您调用new JSONArray(tokener)tokener器不再位于令牌流的开头。 Try creating a new JSONTokener instance for the 2nd attempt at parsing.. 尝试为解析的第二次尝试创建一个新的JSONTokener实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM