首頁  >  文章  >  如何將嵌套 json 物件解包為實體

如何將嵌套 json 物件解包為實體

WBOY
WBOY轉載
2024-02-06 09:48:09549瀏覽
問題內容

我正在呼叫另一個 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刪除