Search code examples
javaspringjacksonobjectmapper

Map nested JSON list to Object array in Spring Boot with Jackson


This is the form of my response JSON.

The top-level is a List, but the Objects I really care about are in the "Results" list, which here is an example of one of them expanded (they are maps). Each "result" is basically a recipe and information pertaining to that recipe. I am currently doing:

ObjectMapper mapper = new ObjectMapper();
Recipe[] recipes = mapper.readValue(json, Recipe[].class);

But it is failing on the first character:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type [Lcom.prepchef.backend.Recipe; from Object value (token JsonToken.START_OBJECT) at [Source: (StringReader); line: 1, column: 1]

I presume because the the "results" section isn't the top-level of the JSON. But I'm not sure how to modify the readValue method to isolate the "results" section.

I would really appreciate any advice on this subject.


Solution

  • This stackoverflow post was helpful. Using JsonNode's at() method, I was able to specify "results" as though it was the top level:

    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(spoonacularResponse.body());
    String sourceString = jsonNode.at("/results").toString();
    Recipe[] recipes = mapper.readValue(sourceString, Recipe[].class);