I have an HttpResponse object for a web request I just made. The response is in the JSON format, so I need to parse it. I can do it in an absurdly complex way, but it seems like there must be a better way.
Is this really the best I can do?
HttpResponse response; // some response object Reader in = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); StringBuilder builder= new StringBuilder(); char[] buf = new char[1000]; int l = 0; while (l >= 0) { builder.append(buf, 0, l); l = in.read(buf); } JSONTokener tokener = new JSONTokener( builder.toString() ); JSONArray finalResult = new JSONArray( tokener );
I'm on Android if that makes any difference.
We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.
If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.
Two things which can be done more efficiently:
StringBuilder
instead of StringBuffer
since it's the faster and younger brother.BufferedReader#readLine()
to read it line by line instead of reading it char by char.HttpResponse response; // some response object BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } JSONTokener tokener = new JSONTokener(builder.toString()); JSONArray finalResult = new JSONArray(tokener);
If the JSON is actually a single line, then you can also remove the loop and builder.
HttpResponse response; // some response object BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); JSONTokener tokener = new JSONTokener(json); JSONArray finalResult = new JSONArray(tokener);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With