-1

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

0

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is ObjectMapper a [Java] class that you wrote?
@Abra no, it a json lib name "Jackson", it kind popular lib in java when you needs operate with json data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.