Android从url解析json并将其存储起来

问题描述:

嗨,那里我创建了我的第一个android应用程序,我想知道从URL解析JSON Feed的最佳和最有效的方式是什么。另外理想情况下,我想将它存储在某个地方,以便我可以在应用程序的不同部分继续使用它。我到处寻找,发现了很多不同的方式,我不知道该去哪。在你看来,什么是有效和容易地解析json的最佳方式?Android从url解析json并将其存储起来

你最好的选择可能是GSON

很简单,速度非常快,容易序列化和JSON对象和POJO,定制之间的反序列化,但通常这是没有必要的,它被设置为很快出现在ADK。同时,您可以将其导入到您的应用中。还有其他的图书馆,但这几乎可以肯定是刚开始接触android和json处理的人的最佳位置,对于其他人而言,这是最好的开始。

如果你想保存你的数据,所以你不必每次都需要下载它,你可以反序列化你的json到一个java对象(使用GSON)并使用ORMLite来简单地将你的对象放入一个sqlite数据库。或者,您可以将json对象保存到一个文件(可能位于cache directory),然后使用GSON作为ORM。

+0

对于GSON +1。这就是我使用的。 – Cody 2012-03-07 16:06:30

+0

超出范围,但为GSON +1:伟大的提示:-) – Pascal 2012-12-17 16:28:29

这很简单example使用listview来显示数据。我使用非常相似的代码来显示数据,但我有一个自定义适配器。如果你只是使用文本和数据,它会正常工作。如果你想要更强大的功能,你可以使用懒惰的图像管理器/图像管理器。

我会在这边看到什么东西,抓住数据然后序列化到磁盘。

下面的代码显示的第一阶段,抓取和分析你的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(); 
+1

我用out.writeObject(jsonObject.toString());和JSONObject jsonObject = new JSONObject((String)in.readObject());因为字符串是可序列化的,但JSONObject不是。 – FR073N 2014-04-11 10:59:05

+1

JSONObject不可序列化,使用它来输出流会引发NotSerializableException。你能否考虑使用有效的可序列化对象编辑答案(可能是JSON字符串表示形式)? – 2014-07-21 10:57:13

由于http请求很耗时,所以使用异步任务将是最好的主意。否则,主线程可能会抛出错误。下面显示的类可以异步下载

private class jsonLoad extends AsyncTask<String, Void, String> { 
    @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;  } 
    } 
    } 

与其他答案不同,此处下载的json字符串本身保存在文件中。所以序列化是没有必要的 现在正在加载从URL的JSON可以做到通过调用

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

这将内容保存到文件中。 打开保存的json字符串

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