Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android parse json from url and store it

Tags:

json

android

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?

like image 905
iamlukeyb Avatar asked Dec 01 '22 00:12

iamlukeyb


1 Answers

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();
like image 59
Ljdawson Avatar answered Dec 04 '22 05:12

Ljdawson