我正在尝试解析android中的以下JSON - http://cj1m.1.ai/test.json
目前,在运行此代码时,我的应用程序崩溃了:
public String getJSON() throws IOException{
String url = "http://cj1m.1.ai/test.json";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
String jsonText = reader.readLine();
return jsonText;
}
我做错了什么,我该如何解决这个问题?
答案 0 :(得分:1)
问题可能是因为JSON响应格式不正确。看起来http://cj1m.1.ai/test.json中的JSON响应不正确。您可以在此网址中验证您的JSON响应 - http://jsonlint.com/
编辑:
从您的最新日志中,很明显您正在尝试在主线程中检索导致应用程序崩溃的JSON。您需要使用AsyncTask
来执行网络操作。
您可以参考此代码,
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
更多详情here!
希望这有帮助。