我在Android應用程序的工作,我需要解析的json對象與數據。您如何看待我創建JSONParser類並嘗試使用asynctask,但出現錯誤,我無法理解問題出在哪裏。每次我使用它resultJSON爲空。希望你能給我一個建議!Android上使用的AsyncTask解析JSON
public class JSONParser {
private String resultJSON;
public JSONArray getJSON(String url) throws JSONException {
Parser parser = new Parser();
parser.execute(url);
return json;
}
private class Parser extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
for (String url : urls) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
resultJSON = builder.toString();
} else {
Log.e(JSONParser.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultJSON;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
json = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
什麼是您的日誌說?它應該有一個堆棧跟蹤或「無法下載文件」,因爲'.toString()'不應該從'StringBuilder'中爲空。 – Eric
由於您的JSONArray不會等待異步任務完成,所以您會收到此錯誤。 –
加'onPostExecute'方法的異步任務和移動'JSONArray JSON =新JSONArray(resultJSON)'行那裏。因爲你應該等到任務完成後,現在你試着解析json,當它尚未下載時。 – vorrtex