简体   繁体   English

反序列化嵌套的Json数组

[英]Deserialize nested Json Arrays

I have some Json which looks like: 我有一些Json,看起来像:

{
  "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". 我对“ foo”和“ foo2”不感兴趣,但只想反序列化“ 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? 如何在不映射我不感兴趣的字段的情况下使用嵌套数组反序列化嵌套Json?

You should map details as a POJO not as List<Details> 您应该将details映射为POJO而不是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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM