Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse JSON from a Java HTTPResponse?

Tags:

java

json

android

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.

like image 699
Joe Ludwig Avatar asked May 16 '10 21:05

Joe Ludwig


People also ask

How do you parse a JSON object in Java?

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.

How do I parse a JSON file?

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.


1 Answers

Two things which can be done more efficiently:

  1. Use StringBuilder instead of StringBuffer since it's the faster and younger brother.
  2. Use 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); 
like image 160
BalusC Avatar answered Sep 21 '22 04:09

BalusC