首页  >  文章  >  如何将嵌套 json 对象解包为实体

如何将嵌套 json 对象解包为实体

WBOY
WBOY转载
2024-02-06 09:48:09562浏览
问题内容

我正在调用另一个 api 并获得以下 json 响应

{
    "metadata": {},
    "data": {
        "productid": 102001,
        "productname": "p101",

        "branddetail": {
            "brandid": 3840,
            "brandname": "abc",
            "brandcode": "x01"
        }
    }
}

如何解开品牌详细信息并将其作为类实体读取,如下所示?

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);
    }

提前致谢


正确答案


使用convertvalue(),这里是一个测试。

@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);
}

以上是如何将嵌套 json 对象解包为实体的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除