本文介绍了如何使用Jackson注释将嵌套值映射到属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我正在调用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"
}
}
我能够映射产品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?
推荐答案
你可以实现这一点:
String brandName;
@JsonProperty("brand")
private void unpackNameFromNestedObject(Map<String, String> brand) {
brandName = brand.get("name");
}
这篇关于如何使用Jackson注释将嵌套值映射到属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!