Android从url解析json并存储

标签 android json

您好,我正在创建我的第一个 Android 应用程序,我想知道从 URL 解析 JSON Feed 的最佳和最有效的方法是什么。此外,理想情况下我想将它存储在某个地方,以便我可以继续前进在应用程序的不同部分返回它。我到处都看过,发现了很多不同的方法,但我不确定该选择哪种。在您看来,高效、轻松地解析 json 的最佳方式是什么?

最佳答案

在这方面我支持 whatsthebeef,获取数据然后序列化到磁盘。

下面的代码展示了第一阶段,抓取 JSON 并将其解析为 JSON 对象并保存到磁盘

// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");

// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();

// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);

// Save the JSONOvject
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFile.srl"));
out.writeObject( jsonObject );
out.close();

将 JSONObject 序列化并保存到磁盘后,您可以随时使用以下方法将其加载回来:

// Load in an object
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(getCacheDir(),"")+"cacheFile.srl")));
JSONObject jsonObject = (JSONObject) in.readObject();
in.close();

关于Android从url解析json并存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9604752/

相关文章:

java - 如何在后台下载文件列表而不影响其他 Activity 的性能?

android - 在 recyclerView 适配器内单击 handle 按钮

android - Android GridView适配器崩溃

安卓,布局 : How do I get my button to overlay existing layout in axml?

javascript - 从 JSON 对象读取元素失败

php - 我正在使用 php 作为后端在 android 中进行推送通知。如何将我的 Sql 数据库值检索到 android 中

javascript - jQuery UI 自动完成 : How to base on JSON data NOT name & Label

java - 在 Java 中展平 JSONObject - 递归导致 StackOverflowError

java - 写入扩展数组

javascript - 检索 getJSON 属性值