3

我正在创建一个从 Internet 获取 JSON 文件的活动(通过 AsyncTask)。我遇到了这个错误:org.json.JSONException: Unterminated string at character...

我检查了我在应用程序中下载的 JSON 文件,发现有一个包含括号的对象。这是可疑的 JSON 对象:

[{ ... }{"id":"5674563646","cat":"Uncategorized","subcat":"Uncategorized","name":"Tecno Lab","desc":"We run open hours from 8-10pm and [most] Saturdays from 12-6pm.","addr":"Main Street","city":"New York","country":"United States"} { ... }]

那么,如何从我的活动中逃脱括号?

这是我下载 JSON 文件的 AsyncTask 的一部分:

protected String doInBackground(String... urls) {
    int timeout = 10;
    int i, count = 0;

    BasicHttpParams basicParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(basicParams, timeout * 1000);
    HttpConnectionParams.setSoTimeout(basicParams, timeout * 1000 );
    DefaultHttpClient client = new DefaultHttpClient(basicParams);

    StringBuilder stringBuilder = new StringBuilder();
    for (i = 0; i < urls.length; i++) {
        HttpGet request = new HttpGet(urls[i]);
        request.addHeader("Cache-Control", "no-cache");

        try {
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            InputStreamReader in = new InputStreamReader(entity.getContent());
            BufferedReader reader = new BufferedReader(in);
            String line = "";

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);

                count++;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        publishProgress(count * 100 / urls.length);
    }
    return stringBuilder.toString();
}

protected void onPostExecute(String result) {
    super.onPostExecute(result);

...
    JSONArray ja = new JSONArray(result);
...
4

1 回答 1

1

JSON 响应通常包含两种括号{}[]但是这两种括号的含义和用途完全不同。而第一个代表 JSON Object,第二个代表 JSON Array。

在您下载的 JSON 文件中,问题与单词无关,[most]因为它位于double quotes. 您的 JSON 输入中的问题是"addr": "Main Street". 那里缺少开头的双引号。

更正 JSON 输入:

{"id":"5674563646","cat":"Uncategorized","subcat":"Uncategorized","name":"Tecno Lab","desc":"We run open hours from 8-10pm and [most] Saturdays from 12-6pm.","addr":"Main Street","city":"New York","country":"United States"}
于 2015-11-24T19:45:46.730 回答