gpt4 book ai didi

java - android使用asynctask解析json

转载 作者:行者123 更新时间:2023-11-30 11:37:23 25 4
gpt4 key购买 nike

我正在开发 android 应用程序,我需要用数据解析我的 json 对象。你怎么看我创建了 JSONParser 类并尝试使用 asynctask,但是出了点问题,我不明白问题出在哪里。每次我使用它时,resultJSON 都是空的。希望大家多多指教!

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();
}
}
}
}

最佳答案


你为什么不 JSONArray json = new JSONArray(resultJSON); 在异步任务的执行后方法上执行此操作。

而且我不会建议使用 varevarao 方式,因为它会给一个线程带来额外的负担。

关于java - android使用asynctask解析json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14074795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com