4

Hi there i'm creating my first android app and i'm wanting to know what is the best and most efficient way of parsing a JSON Feed from a URL.Also Ideally i want to store it somewhere so i can keep going back to it in different parts of the app. I have looked everywhere and found lots of different ways of doing it and i'm not sure which to go for. In your opinion whats the best way of parsing json efficiently and easily?

4 Answers 4

12

I'd side with whatsthebeef on this one, grab the data and then serialize to disk.

The code below shows the first stage, grabbing and parsing your 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();

Once you have the JSONObject serialized and save to disk, you can load it back in 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();
Sign up to request clarification or add additional context in comments.

2 Comments

I used out.writeObject( jsonObject.toString() ); and JSONObject jsonObject = new JSONObject((String) in.readObject()); because String is serializable, but JSONObject not.
JSONObject is not serializable, using it to an output stream will raise NotSerializableException. Could you please consider to edit the answer using a valid serializable object (maybe the JSON string representation)?
7

Your best bet is probably GSON

It's simple, very fast, easy to serialize and deserialize between json objects and POJO, customizable, although generally it's not necessary and it is set to appear in the ADK soon. In the meantime you can just import it into your app. There are other libraries out there but this is almost certainly the best place to start for someone new to android and json processing and for that matter just about everyone else.

If you want to persist you data so you don't have to download it every time you need it, you can deserialize your json into a java object (using GSON) and use ORMLite to simply push your objects into a sqlite database. Alternatively you can save your json objects to a file (perhaps in the cache directory)and then use GSON as the ORM.

1 Comment

Out of Scope, but +1 for GSON: great hint :-)
0

This is pretty straightforward example using a listview to display the data. I use very similar code to display data but I have a custom adapter. If you are just using text and data it would work fine. If you want something more robust you can use lazy loader/image manager for images.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.