Search code examples
javajsonspringresttemplateobjectmapper

Spring RestTemplate Map specific key value inside JSON response to POJO class


I have an API, which returns JSON in this format:

 {
      "errors": null,
      "someKey1": "someValue1",
      "someKey2": "someValue2",
      "response": {
          "id": 21,
          "key1": "value1",
          "key2": "value2",
          "key3": "value3",
          "key4": {
              "key5": [
                  {
                      "ABC": "abc",
                      "XYZ": 1,
                      "PQR": "pqr"
                  },
                  {
                      "ABC": "abc",
                      "XYZ": 3,
                      "PQR": "pqr"
                  }
              ]
          },
          "key6": "value6"
      }
    }

I also have a POJO class which has fields corresponding to the response key of the JSON response because the someKey1, someKey2 and errors key are not relevant in my use case.

Is it possible to map the JSON response to my Java POJO class i.e to map only the values inside the response key ?

One possible approach is to accept a String response and map it to my POJO using setter methods.

String apiResponse = restTemplate.exchange(someUrl, HttpMethod.GET, new HttpEntity<>(authHeader), String.class).getBody();
JSONObject jsonObject = new JSONObject(apiResponse);
MyObject myObject = buildNewObject(jsonObject.get("response"));

Is there a better way. Something like this ? :

ResponseEntity<MyObject> responseEntity = restTemplate.exchange(someUrl, HttpMethod.GET, new HttpEntity<>(authHeader), MyObject.class).getBody().get("response");

Solution

  • You can create a Mapper class with your POJO as one object and other extra values as variables , Shown below

    class Mapper{
    
    private PojoClass response;
    private String someKey1;
    private String somekey2;
    private String errors;
    
    //Create getters and setters
    
    }
    

    Now the response will automatically bind to POJO and other values will bind to corresponding key1 key2 and errors