我正在调用另一个 api 并得到以下 json 响应
{
"metadata": {},
"data": {
"productId": 102001,
"productName": "P101",
"brandDetail": {
"brandId": 3840,
"brandName": "ABC",
"brandCode": "X01"
}
}
}
如何解开品牌详细信息并将其作为类实体读取,如下所示?
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);
}