javaobjectmapper

How to unwrap nested json object as an entity


I am calling another api and get the below json response

{
    "metadata": {},
    "data": {
        "productId": 102001,
        "productName": "P101",

        "brandDetail": {
            "brandId": 3840,
            "brandName": "ABC",
            "brandCode": "X01"
        }
    }
}

How do I unwrap the brand details and read it as a class entity like below?

    HttpGet httpGet = buildHttpGet("/externalApiURL");
    HttpResponse response = getHttpClient().execute(httpGet);
    HttpEntity entity = response.getEntity();

    if (entity != null && response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
        ObjectMapper objectMapper = new ObjectMapper();
        BrandDetail brandDetail = objectMapper.readValue(entity.getContent(), BrandDetail.class);
    }

Thanks in advance


Solution

  • Use the convertValue(), here is an test.

    @Data
    public class BrandDetail {
        private int brandId;
        private String brandName;
        private String brandCode;
    }
    
    @Test
    public void demo() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        var data = """
                {
                    "metadata": {},
                    "data": {
                        "productId": 102001,
                        "productName": "P101",
                        "brandDetail": {
                            "brandId": 3840,
                            "brandName": "ABC",
                            "brandCode": "X01"
                        }
                    }
                }
                """;
        JsonNode node = mapper.readTree(data);
        JsonNode brandNode = node.get("data").get("brandDetail");
        BrandDetail brandDetail = mapper.convertValue(brandNode, BrandDetail.class);
        // BrandDetail(brandId=3840, brandName=ABC, brandCode=X01)
        System.out.println(brandDetail);
    }