如何使用 Jackson 注释将嵌套值映射到属性? [英] How to map a nested value to a property using Jackson annotations?
问题描述
假设我正在调用一个 API,该 API 以产品的以下 JSON 进行响应:
Let's say I'm making a call to an API that responds with the following JSON for a product:
{
"id": 123,
"name": "The Best Product",
"brand": {
"id": 234,
"name": "ACME Products"
}
}
我可以使用 Jackson 注释很好地映射产品 ID 和名称:
I'm able to map the product id and name just fine using Jackson annotations:
public class ProductTest {
private int productId;
private String productName, brandName;
@JsonProperty("id")
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
@JsonProperty("name")
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
}
然后使用 fromJson 方法创建产品:
And then using the fromJson method to create the product:
JsonNode apiResponse = api.getResponse();
Product product = Json.fromJson(apiResponse, Product.class);
但现在我想弄清楚如何获取品牌名称,这是一个嵌套属性.我希望这样的事情会奏效:
But now I'm trying to figure out how to grab the brand name, which is a nested property. I was hoping that something like this would work:
@JsonProperty("brand.name")
public String getBrandName() {
return brandName;
}
但当然没有.有没有一种简单的方法可以使用注释来完成我想要的操作?
But of course it didn't. Is there an easy way to accomplish what I want using annotations?
我试图解析的实际 JSON 响应非常复杂,我不想为每个子节点创建一个全新的类,即使我只需要一个字段.
The actual JSON response I'm trying to parse is very complex, and I don't want to have to create an entire new class for every sub-node, even though I only need a single field.
推荐答案
你可以这样实现:
String brandName;
@JsonProperty("brand")
private void unpackNameFromNestedObject(Map<String, String> brand) {
brandName = brand.get("name");
}
这篇关于如何使用 Jackson 注释将嵌套值映射到属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!