android parse json,Android parse json from url and store it

该博客介绍了如何使用Android的AsyncTask类来异步下载JSON数据,避免主线程阻塞。通过创建一个名为jsonLoad的内部类,它继承自AsyncTask,实现了后台下载并在完成后将数据保存到本地文件。下载过程包括HTTP请求、处理响应并将其写入文件。之后,可以从文件中读取并解析JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Since an http request is time consuming, using an async task will be the best idea. Otherwise the main thread may throw errors. The class shown below can do the download asynchronously

private class jsonLoad extends AsyncTask {

@Override

protected String doInBackground(String... urls) {

String response = "";

for (String url : urls) {

DefaultHttpClient client = new DefaultHttpClient();

HttpGet httpGet = new HttpGet(url);

try {

HttpResponse execute = client.execute(httpGet);

InputStream content = execute.getEntity().getContent();

BufferedReader buffer = new BufferedReader(new InputStreamReader(content));

String s = "";

while ((s = buffer.readLine()) != null) {

response += s;

}

} catch (Exception e) {

e.printStackTrace();

}

}

return response;

}

@Override

protected void onPostExecute(String result) {

// Instantiate a JSON object from the request response

try {

JSONObject jsonObject = new JSONObject(result);

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

File file = new File(getApplicationContext().getFilesDir(),"nowList.cache");

try {

file.createNewFile();

FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE);

writer.write(result);

writer.flush();

writer.close();

}

catch (IOException e) { e.printStackTrace(); return false; }

}

}

Unlike the other answer, here the downloaded json string itself is saved in file. So Serialization is not necessary

Now loading the json from url can be done by calling

jsonLoad jtask=new jsonLoad ();

jtask.doInBackground("http:www.json.com/urJsonFile.json");

this will save the contents to the file.

To open the saved json string

File file = new File(getApplicationContext().getFilesDir(),"nowList.cache");

StringBuilder text = new StringBuilder();

try {

BufferedReader br = new BufferedReader(new FileReader(file));

String line;

while ((line = br.readLine()) != null) {

text.append(line);

text.append('\n');

}

br.close();

}

catch (IOException e) {

//print log

}

JSONObject jsonObject = new JSONObject(text);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值