In my Android client I want to receive JSON objects from a server. By googling I found a lot of different possibilities how to best parse the InputStream from the Server, but most of them wrote their own parser. Isn't there a library which does this parsing for me? Or how should I best implement it by myself?
+1
A:
You could use the built in JSONTokener. There is an example in that link showing how to use it.
To get response as string:
InputStream stream = httpResponse.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
String result = sb.toString();
Mayra
2010-08-25 20:39:32
Yes thanks! That is nice if i already have the string of the json object. but part of my problem is that i don't really know the best way to cast the HttpResponse into a String correctly.
Roflcoptr
2010-08-25 20:45:13
Ah, yeah, thats can be a pain. See edit. Basically you get the contents as an inputstream, and then turn that into a string.
Mayra
2010-08-25 21:14:41
+1
A:
There is not, yet, any package in the Sun Java distribution for parsing JSON, and I am not aware of any in Android's class library either.
I have a very lightweight JSON parser which you can use to parse an HTTP content stream. It's completely free, use at your own risk, etc, etc,. Details and download on my website. It should work just fine in the Android VM.
Software Monkey
2010-08-25 20:47:34
A:
The Wiktionary example in the SDK gets the contents as an InputStream, turns it into a String, then constructs a new org.json.JSONObject(String) to parse through the result.
Buck Fury
2010-08-25 21:51:53
+1
A:
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
u can parse the input to json by this code... hope this will be useful for you
Adhavan
2010-10-29 06:53:52