Home > Back-end >  How would I use Jackson to flatten JSON with nested array?
How would I use Jackson to flatten JSON with nested array?

Time:01-28

I am using JackSon to parse the following JSON:

{
    "AwardID": "1111111",
    "AwardTitle": "Test Title",
    "Effort": 
        "[
            {
                "PersonFirstName": "Jon",
                "PersonLastName": "Snow"
            }
        ]"
}

I would like to flatten this to be used in the following class:

public class Award {
    private String awardId;
    private String awardTitle;
    private String personFirstName;
    private String personLastName;
}

I have tried the following and have gotten the first two values, but I haven't been able to get the values from Effort trying to use JsonUnwrapped. I noted that it doesn't work with arrays, but I am trying the objectMapper.configure(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS, true) configuration in the main method used to get the values.

public class Award {
    @JsonProperty("AwardID")
    private String awardId;

    @JsonProperty("AwardTitle")
    private String awardTitle;

    @JsonUnwrapped
    private Effort effort;
}

public class Effort {
    private String personFirstName;
    private String personLastName;
}

Note that I only expect one value in the Effort array from the API response at this time.

What is recommended to try next? Thank you!

CodePudding user response:

The easiest way is having a List<Effort> if you have a JSON Array.

If there is always 1 item for Effort, the returning JSON should not have Effort as a JSON Array and instead should be a JSON Object.

But if you can only handle it codewise, you can have something like this (Note that there should always contain one item in Effort, otherwise it will throw Exception):

public class Award {
    @JsonProperty("AwardID")
    private String awardId;

    @JsonProperty("AwardTitle")
    private String awardTitle;

    @JsonProperty("Effort")
    private Effort effort;
}

public class Effort {
    @JsonProperty("PersonFirstName")
    private String personFirstName;

    @JsonProperty("PersonLastName")
    private String personLastName;
}

And your ObjectMapper needs to be enabled with DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS as well:

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
Award award = mapper.readValue(rawJson, Award.class); // rawJson is your JSON String

And it should have the following output:

Award(awardId=1111111, awardTitle=Test Title, effort=Effort(personFirstName=Jon, personLastName=Snow))

Note that the annotation @JsonUnwrapped can only apply on JSON Object, not JSON Array:

Value is serialized as JSON Object (can not unwrap JSON arrays using this mechanism)

  • Related