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

时间:2013-03-30 13:12:10

标签: java json parsing rest

我正在使用以下代码处理来自我的服务器的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();
            }

        }
    }

如果响应是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"}]

1 个答案:

答案 0 :(得分:2)

我预计失败的原因是,当您致电new JSONArray(tokener)时,tokener不再位于令牌流的开头。尝试为解析的第二次尝试创建一个新的JSONTokener实例。