我正在创建一个从Internet获取JSON文件的活动(通过AsyncTask)。 我遇到了这个错误: org.json.JSONException:字符处未终止的字符串...
我检查了我在应用程序中下载的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);
...
答案 0 :(得分:1)
JSON响应通常包含两种括号{}
和[]
,但两个括号具有完全不同的含义和用法。而第一个代表JSON对象,第二个代表JSON数组。
在您下载的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"}