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" } }
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; } }
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?
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.
Mapping With Annotations To map the nested brandName property, we first need to unpack the nested brand object to a Map and extract the name property. To map ownerName, we unpack the nested owner object to a Map and extract its name property.
A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.
Jackson Serialization AnnotationsThis annotation tells Jackson to use this method to generate the JSON string from the Java object. annotation, you can define the way in which the Java object is to be serialized. Note: Jackson omits any quotation marks inside the String that is returned by the custom serializer.
You can achieve this like that:
String brandName; @JsonProperty("brand") private void unpackNameFromNestedObject(Map<String, String> brand) { brandName = brand.get("name"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With