您好,我正在创建我的第一个 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/