I need to parse a remote response from a URL that retrieves a big JSON object and store it locally so we can perform searches for example, in an activity in Android.
I've been trying to look it up but I can't find any approach about how to do it.
Any suggestion/help please?
Thanks a lot in advance!
You can use Gson parsing to parse the JSON from url.
For Storing the result use sqlite Database.
Here is the good example for GSON parsing
For sqlite follow this link
the retrieved JSON response is stored in the BufferReader i.e.,
urlClientStream = openHttpClientPostConnection(searchURL,
urlParams.toString());
BufferedReader reader = new BufferedReader(
new InputStreamReader(urlClientStream), 8192);
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
JSONObject mainObj = new JSONObject(buffer.toString())
.getJSONObject("RESPONSE");
Hope this helps you
Related
I am using an application which parse remote json into a list view and it works fine as single activity and if the device is online..
Is there a way to download the json data locally(cached) in the device and then pull it inside my app inside Listviews.. i am planning to have multiple listviews which takes the data from the same json file and then filter them out based on some criteria such as location then allow user to swipe the app for different views.
I appreciate your advices,
Abdul
I have one idea , i hope it will work for you
Store content of file in Object that is in cache in form of JSON .
Now Object have all your content which you can pass to JsonArray or JsonObject to parse.
File file = new File("C:/ciphertext.txt");
int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
while ((ch = fin.read()) != -1)
strContent.append((char) ch);
fin.close();
} catch (Exception e) {
System.out.println(e);
}
Now our strContent have content of file.
You can store the data in SharedPreference.
Check this out
And also, there are more Storage Options for you.
I have a PHP JSON that sends me JSONArray.
public JSONArray lastTweet()throws ClientProtocolException,IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
return timeline;
}
return null;
}
I can get Object and values from this JSONArray (timeline), but it work only then application have internet conection. I want to save this JSON in my internal storage like a json file and after work with this file in offline mod. How i can do this?
Try using JSON Simple library which allows easy encoding/decoding of JSON files.
Examples: Encoding
Then it's just plain:
try {
outStream = openFileOutput("tweet.json", Context.MODE_PRIVATE);
outStream.write(json.getJSONString().getBytes());
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
However if you do not want to store it for forever, or for re-sending purposes, I recommend using Cache
Mind that cache can be automatically wiped, so it's up to you. More on this, as always, on the Android developers site: Android: Saving Files # Write Internal Storage
UPDATE:
Turns out that android JSONObject.toString() produces coherent JSON output that can be saved to a file the way desciber above, without any 3rd party library, however you would need to marshall it back to JSONObject/Array/Primitive by yourself, and that will take some extra work.
I'm new to the android world and i have some problem.
I'm developing a project under android and it require a json parser. I get my json file from a web service developed under Zend framework, the link to the web service : "manganew:8080/wsmanganew/manga/manga/idmanga/1" and the content of the json file is
{
"manga": [
{
"idmanga":"1",
"titre":"naruto",
"episode":"145",
"url":"http:\/\/naruto.com\/",
"image":null,
"description":"Naruto Shippuuden .",
"tv":"TV Tokyo",
"dtdebut":"2013-05-23 12:30:00",
"iduser":"1"
}
]}
I'm following this tutorial "http://www.androidhive.info/2012/01/android-json-parsing-tutorial/".
i don't know how index to the web service link in the android, any help will be useful.
thank you
so, what do you need to do? download json object from that url into your app?
that code has method getJSONFromUrl in it's class, you should use it
though, according to comments it has flaws in it.
to read string from file use this code
BufferedReader reader = new BufferedReader(new FileReader("/mnt/sdcard/docs/file.json"));
String line, results = "";
while( (line = reader.readLine()) != null)
results += line;
reader.close();
JSONObject obj = new JSONObject(results);
replace path with path to your file
try this
BufferedReader reader = new BufferedReader(new FileReader("C:\\file.json"));
String line, results = "";
while( (line = reader.readLine()) != null)
results += line;
reader.close();
JSONObject obj = new JSONObject(results);
Replace with your local machine download field path C:\\file.json
I have a servlet that has the following purpose:
Receive data via the URL (that is, using get). Then returns a message, based on this input, back to the caller. I am new to this stuff, but have come to learn that using json (actually, Gson) is suitable for this.
My question now is, how do I retrieve this json message? What URL do I target? The relevant lines in the servlet are:
String json = new Gson().toJson(thelist);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().println(json);
This is how I try to retrieve the json:
try{
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://AnIPno:8181/sample/response?first=5&second=92866");
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
e.printStackTrace();
}
But apparently this does not work, as I have found jsonObject has a size of 0 (it should be an array with three elements).
Previously, I had a write() instead of println() in the servlet. I'm not sure if that matters in this case. But I'm assuming I've misunderstood something about how the json object is retrieved. Is it not enough to point it towards the URL of the servlet?
Reading an InputStream whether from a File on the file system or from an HTTP request is, in most cases, the same.
What you have is correct only if your servlet wrote a single line. If the Gson object toString() method returns multiple lines, you're going to have to read multiple lines from the InputStream. I like to use the Scanner class for reading from an InputStream.
try {
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://localhost:8080/cc/jsonyeah");
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
Scanner scanner = new Scanner(httpResponse.getEntity().getContent(), "UTF-8");
while(scanner.hasNextLine()) { // scanner looks ahead for an end-of-line
json += scanner.nextLine() + "\n"; // read the full line, you can append a \n
}
// do your serialization
} catch(Exception e) {
e.printStackTrace();
}
So we've done the same thing we would've done if we were reading from a file. Now the json object contains the json you received from the servlet, as a String.
For the serialization, you have a few options.
A Gson object has an overloaded method fromJson() that can take a String or a Reader, among other things.
From where we are with the code above, you can do
MyClass instance = new Gson().fromJson(json, MyClass.class);
where MyClass is the type you are trying to create. You will have to use a TypeToken for generic classes (such as a list). TypeToken is an abstract class, so generate an anonymous class and call getType()
Type type = new com.google.gson.reflect.TypeToken<List<String>>(){}.getType();
List<MyClass> list = new Gson().fromJson(json, type);
Another option is to use the overloaded method that takes a Reader directly instead of reading line by line from the InputStream:
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
MyClass instance = new Gson().fromJson(reader , MyClass.class);
You'll get to skip a step.
Don't forget to close your streams.
I have this function to readJsonData from a a request to a JSON String. You can use this function to retrieve the JSON, then use GSON to parse it to the object that you like. It works for my application. Hope it works for you too.
protected String readJson(HttpResponse resp)
throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
resp.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
} finally {
if (reader != null)
reader.close();
}
return buffer.toString();
}
So based on your code. I guess this should work:
String jsonData = readJson(httpResponse);
YourObject obj = new Gson().fromJson(jsonData, YourObject.class);
Before trying this, make sure your servlet prints out the JSON data that you want. I suggest using these Chrome Extensions: Postman - REST Client and JSON Formatter, to test your data from servlet. It's pretty helpful.
My server returned the following string using the jsonencode() in the php code after sending a POST passing variables for the query.
{"distance":"0.00194210443015968","usrlat":"38.5817","usrlong":"-77.3245","globalid":"245"}{"distance":"4.94445650874035","usrlat":"38.6501","usrlong":"-77.2975","globalid":"233"}{"distance":"4.94445650874035","usrlat":"38.6501","usrlong":"-77.2975","globalid":"242"}
Code:
try
{ etc.. connection details..
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
//Convert response to a string
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server will be stored in response variable.
response = sb.toString();
//try parse the string to a JSON object
try{
jObject = new JSONObject(response);
}catch(JSONException e){...
Background - This simple bit of code has produced a jObject which holds only the first element (object) from response. I have tried changing the reponse to an jArray by inserting square brackets before and after, however the elements (objects) from the response are not seperated by a comma. Considered interating through the response to insert comma's however the same root problem exists... parsing and interation. Additionally, I have created a class with properties according to the response. No luck there because the same root problem exist...Parsing and iteration. I have scoured the net, only to discover that JSON is an extremely easy and lite weight alt to XML. I have visted my local book store to discover that JSON is not a book worthy topic...yet. Finally, I have turned to GSON for some clarity.
Question - Using JSON or GSON how do I deserialize and iterate through the response to create useable objects in my android application? Am I asking the right question in my search for a solution?
You basically hit on your issue - that the text is not a valid JSON array. So you have two options:
Preprocess the JSON to make it a valid JSON array
Read each line one by one and create a JSONObject for each line, then manually add each object to a JSONSArray or a plain old java array or collection
FYI - This assumes you have no control over the server side. If you do, change that code to make it a valid JSON array