TIL: Pulling Values Out of JSON Response in Java

This is a continuation from the work I was doing yesterday with experimenting with making requests in spring applications. I wanted to see how I could parse the response message and pull out the data from it.

My initial investigation into this took me down a path of trying to map the received payload to a defined data model. I think this was referred to deserializing or something like that. I came across a github page where someone had done benchmarking a whole lot of various packages that are built for solving this problem (the most popular being Jackson evidently). Here’s a link to that break down.

Jackson seemed to be a bit of overkill for what I wanted (and where my skill level is currently at). So I went back to doing some more searching. I eventually came across a way to just pick off the values from a response that you’re interested in. Here’s the article that I found covering this (no idea who/what temboo is).

The basic idea is that you can create new JSONObject and JSONArray objects based on the data that’s returned in the response message. You can then step down through nested items that are in the response by creating new objects of those types until you reach the value you’re looking for. Then you can simply assign the value to the correct type and then move on with what you need to do.

I implemented this in a very simple test scenario (building off from yesterday). The API that I’m using returns things in the following format:

1
{"type":"success","value":{"id":6,"quote":"It embraces convention over configuration, providing an experience on par with frameworks that excel at early stage development, such as Ruby on Rails."}}

So I created a test to rip out each of those response values:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
   @Test
   public void ParseJSONResponse() throws Exception {
       RestTemplate restTemplate = new RestTemplate();
       ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

       JSONObject result = new JSONObject(response.getBody());
       String type = result.getString("type");
       JSONObject value = result.getJSONObject("value");
       int id = value.getInt("id");
       String quote = value.getString("quote");

       assertNotNull(response);
       assertEquals(response.getStatusCode(), HttpStatus.OK);
       assertEquals(type, "success");
       assertNotNull(id);
       assertNotNull(quote);
   }

This allowed me to pick through and grab specifically what I wanted. Of course this really only works if you know exactly what you’re going to be getting, but then again you’d hit the same problem if you were mapping to an object so…

I still don’t understand any of this well enough yet, but here I am so far.

💚