How do I parse JSON from a Java HTTPResponse?
- by Joe Ludwig
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.