Best practice to parse a JSON object on the client in Java & Android
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?
Are you kidding me? There are more than a dozen JSON parsers on Java platform, and most work fine on Android (see http://json.org/). Two most commonly recommended choices are Jackson and Gson, and both work nicely to allow you to not only parse and write JSON, but to also bind JSON data directly to and from POJOs.
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();
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
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.
There is not, as of Java 7, any package built into the Sun Oracle Java distribution for parsing JSON; for android there is at least org.json
, though apparently some developers don't like it.
There are, of course, many third-party options.
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.
精彩评论