1

I have some Json which looks like:

{
  "foo": [
    {
      "bar": "baz"
    }
  ],
  "foo2": [
    {
      "bar": "baz"
    }
  ],
  "dishes": [
    {
      "name": "tonno",
      "details": {
        "toppings": [
          "cheese",
          "tomato",
          "tuna"
        ],
        "price": 10
      }
    },
    {
      "name": "cheese",
      "details": {
        "toppings": [
          "cheese",
          "tomato"
        ],
        "price": 5
      }
    },
    {
      "name": "mexicana",
      "details": {
        "toppings": [
          "cheese",
          "tomato",
          "chicken"
        ],
        "price": 12,
        "inOffer": true
      }
    }
  ]
}

I'm not interested in "foo" and "foo2" but only want to deserialize "dishes". For this I created two classes:

public class Dish {

    @JsonProperty("name")
    private String name;

    @JsonProperty("details")
    private List<Detail> details;
}

and

public class Detail {

    @JsonProperty("toppings")
    private List<String> toppings;

    @JsonProperty("price")
    private int price;

    @JsonProperty("inOffer")
    private boolean inOffer;
}

I found this approach and tried the following:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final JsonNode response = mapper.readTree(json).path("dishes");
final CollectionType collectionType = TypeFactory.defaultInstance().constructCollectionType(List.class, Dish.class);
List<Dish> dishes = mapper.readerFor(collectionType).readValue(response);

However, if I run this, I get

m.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token  at [Source: UNKNOWN; line: -1, column: -1]

How can I deserialize nested Json with a nested array without having to map fields I'm not interested in?

2 Answers 2

2

You should map details as a POJO not as List<Details>

public class Dish {

@JsonProperty("name")
private String name;

@JsonProperty("details")
private Detail details;

}
Sign up to request clarification or add additional context in comments.

Comments

0

you may try this:

JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Dish.class);
List<Dish> dishes = mapper.readValue("jsonString", javaType);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.