Mapping Nested Values with Jackson

I just announced the new Spring 5 modules in REST With Spring:

1. Overview

A typical use case when working with JSON is to perform a transformation from one model into another. For example, we might want to parse a complex, densely nested object graph into a more straightforward model for use in another domain.

In this quick article, we’ll look at how to map nested values with Jacksonto flatten out a complex data structure. We’ll deserialize JSON in three different ways:

4. Simplified Domain Model

In a flattened domain model described by the Product class below, we’ll extract brandName, which is nested one level deep within our source JSON. Also, we’ll extract ownerName, which is nested two levels deep and within the nested brand object:

5. 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. Then to map ownerName, we unpack the nested owner object to a Map and extract its name property.

We can instruct Jackson to unpack the nested property by using a combination of @JsonProperty and some custom logic that we add to our Product class: