Android parse json from url and save it

Hi, I am creating my first Android app and I want to know what is the best and most efficient way to parse a JSON feed from a URL. Also, ideally, I want to store it somewhere so that I can continue to go back to it in different parts of the application. I searched everywhere and found many different ways to do this, and I'm not sure what to go for. In your opinion, the best way to parse json is efficient and easy?

+4
source share
4 answers

I would say that with this, take the data and then serialize to disk.

The code below shows the first step, capturing and parsing JSON into a JSON object and saving to disk

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

After the JSONObject is serialized and saved to disk, you can load it back at any time using:

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

Best likely gson

It is simple, very fast, easy to serialize and deserialize between json and POJO objects, it is configurable, although this is usually not necessary, and it will soon appear in the ADK. In the meantime, you can simply import it into your application. There are other libraries, but this is almost certainly the best place to start for someone new in handling android and json, and for that matter almost everyone else.

If you want data to be saved to you so that you do not have to load it every time you need it, you can deserialize your JSON into a Java object (using GSON) and use ORMLite to simply insert your objects into the sqlite database. Alternatively, you can save your json objects to a file (possibly in a directory), and then use GSON as an ORM.

+7
source

This is a fairly simple example , using a list to display data. I use very similar code to display data, but I have a custom adapter. If you just use text and data, it will work fine. If you want something more reliable, you can use the lazy upload / image manager for images.

0
source

Since the HTTP request is time consuming, the best solution would be to use the async task. Otherwise, the main thread may cause errors. The class shown below can do asynchronous loading

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

Unlike the other answer, here the loaded json string itself is saved in a file. So serialization is not needed Now loading 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 in a file. To open a 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); 
0
source

Source: https://habr.com/ru/post/1400233/