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?
You should map details
as a POJO not as List<Details>
public class Dish {
@JsonProperty("name")
private String name;
@JsonProperty("details")
private Detail details;
}
you may try this:
JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Dish.class);
List<Dish> dishes = mapper.readValue("jsonString", javaType);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.