Android Parse Json From Url And Store It
Solution 1:
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 ClientDefaultHttpClientdefaultClient=newDefaultHttpClient();
// Setup the get requestHttpGethttpGetRequest=newHttpGet("http://example.json");
// Execute the request in the clientHttpResponsehttpResponse= defaultClient.execute(httpGetRequest);
// Grab the responseBufferedReaderreader=newBufferedReader(newInputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
Stringjson= reader.readLine();
// Instantiate a JSON object from the request responseJSONObjectjsonObject=newJSONObject(json);
// Save the JSONOvjectObjectOutputout=newObjectOutputStream(newFileOutputStream(newFile(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 objectObjectInputStreamin = newObjectInputStream(newFileInputStream(newFile(newFile(getCacheDir(),"")+"cacheFile.srl")));
JSONObject jsonObject = (JSONObject) in.readObject();
in.close();
Solution 2:
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.
Solution 3:
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.
Solution 4:
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
privateclassjsonLoadextendsAsyncTask<String, Void, String> {
@OverrideprotectedStringdoInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = newDefaultHttpClient();
HttpGet httpGet = newHttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = newBufferedReader(newInputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@OverrideprotectedvoidonPostExecute(String result) {
// Instantiate a JSON object from the request responsetry {
JSONObject jsonObject = newJSONObject(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = newFile(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(); returnfalse; }
}
}
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=newjsonLoad ();
jtask.doInBackground("http:www.json.com/urJsonFile.json");
this will save the contents to the file. To open the saved json string
File file = newFile(getApplicationContext().getFilesDir(),"nowList.cache");
StringBuilder text = newStringBuilder();
try {
BufferedReader br = newBufferedReader(newFileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//print log
}
JSONObject jsonObject = newJSONObject(text);
Post a Comment for "Android Parse Json From Url And Store It"