Parsing JSON from HttpClient request using JSON.org parser
You can get the JSON from the Entity in the HttpResponse using HttpResponse#getEntity. Once you have that, then just create a new JSONArray and iterate the array to access the values in your JSON object:
String json = IOUtils.toString(response.getEntity().getContent());JSONArray array = new JSONArray(json);for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); log.info("the id is {}", object.getInt("id")); log.info("the insertDate is {}", object.getString("insertDate")); log.info("read is {}", object.getBoolean("read")); log.info("the site is {}", object.getString("site")); log.info("the Email is {}", object.getString("Email")); log.info("the location is {}", object.getString("location"));}
I saved the JSON in a JSONBlob at http://jsonblob.com/537a43bfe4b047fa2ef5f15d and created a unit test that requests that JSON:
import lombok.extern.slf4j.Slf4j;import org.apache.commons.io.IOUtils;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.HttpClientBuilder;import org.json.JSONArray;import org.json.JSONObject;import org.junit.Test;@Slf4jpublic class JsonTest { @Test public void test() throws Exception { HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("http://jsonblob.com/api/jsonBlob/537a43bfe4b047fa2ef5f15d"); request.addHeader("accept", "application/json"); HttpResponse response = client.execute(request); String json = IOUtils.toString(response.getEntity().getContent()); JSONArray array = new JSONArray(json); for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); log.info("the id is {}", object.getInt("id")); log.info("the insertDate is {}", object.getString("insertDate")); log.info("read is {}", object.getBoolean("read")); log.info("the site is {}", object.getString("site")); log.info("the Email is {}", object.getString("Email")); log.info("the location is {}", object.getString("location")); } }}
And the output from running it is:
11:23:19.508 [main] INFO JsonTest - the id is 12345611:23:19.516 [main] INFO JsonTest - the insertDate is 2014-05-12T16:51:38.34311:23:19.516 [main] INFO JsonTest - read is false11:23:19.516 [main] INFO JsonTest - the site is acme.com11:23:19.516 [main] INFO JsonTest - the Email is john.doe@acme.com11:23:19.516 [main] INFO JsonTest - the location is /customer/1212?v=1.0
I used the IOUtils class to convert the InputStream from the HttpResponse Entity, but this can be done anyway you like (and converting it like I did may not be the best idea depending on how big the JSON is).