0

I am currently working on a project where i need to make a rest call to an external API and parse the JSON response to a POJO and return back the POJO as JSON for another rest request. I am able to parse the JSON response, but my requirement is to parse only one particular node from it. How can i achieve this? I am using Spring Boot and Spring Rest Template to make the external rest call. Please help!!!

@RestController
public class ProductsController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProductsController.class);

     @RequestMapping(value = "/myRetail/product/{id}", method = RequestMethod.GET, produces = {
                MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.APPLICATION_XML_VALUE })
        @ResponseBody
        public Item getSchedule(@Valid Payload payload) {

         String URL = "<External API>";

         LOGGER.info("payload:{}", payload);
         Item response = new Item();
         RestTemplate restTemplate = new RestTemplate();

         Item item = restTemplate.getForObject(URL, Item.class);

         LOGGER.info("Response:{}", item.toString());
            return response;
        }

}

JSONResponse (This is a part of whole i receive)
{
    "ParentNode": {
        "childNode": {
            "att": "13860428",
            "subchildNode 1": {
                "att1": false,
                "att2": false,
                "att3": true,
                "att4": false
            },
            "att4": "058-34-0436",
            "att5": "025192110306",
            "subchildenode2": {
                "att6": "hello",
                "att7": ["how are you", "fine", "notbad"],
                "is_required": "yes"
            },
            ............
}

Required JSONpart from the above whole response:
"subchildenode2": {
                    "att6": "hello",
                    "att7": ["how are you", "fine", "notbad"],
                    "is_required": "yes"
                }
user3463832
  • 15
  • 1
  • 10

2 Answers2

0

Use the org.json library. With this library you can parse the payload to a JSONObject and navigate to your required subpart of the document.

So you have to get the payload as a JSON-String and parse it to the JSONObject from the library. After that you can navigate to your required subpart of the document and extract the value and then parse it to your required Java POJO.

Have look at: How to parse JSON

rieckpil
  • 10,470
  • 3
  • 32
  • 56
0

Just map the path to the needed object:

{
    "ParentNode": {
        "childNode": {
            "subchildenode2": {
                "att6": "hello",
                "att7": ["how are you", "fine", "notbad"],
                "is_required": "yes"
            }
        }
}

And then simply:

Response responseObject= new Gson().fromJson(json, Response.class);
SubChildNode2 att6 = responseObject.getParentNode().getChildNode().getSubChildNode2();
UGligovic
  • 1
  • 2