簡體   English   中英

反序列化嵌套的Json數組

[英]Deserialize nested Json Arrays

我有一些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
      }
    }
  ]
}

我對“ foo”和“ foo2”不感興趣,但只想反序列化“ dishes”。 為此,我創建了兩個類:

public class Dish {

    @JsonProperty("name")
    private String name;

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

public class Detail {

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

    @JsonProperty("price")
    private int price;

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

我找到了這種方法,並嘗試了以下方法:

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);

但是,如果運行此命令,我將得到

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]

如何在不映射我不感興趣的字段的情況下使用嵌套數組反序列化嵌套Json?

您應該將details映射為POJO而不是List<Details>

public class Dish {

@JsonProperty("name")
private String name;

@JsonProperty("details")
private Detail details;

}

您可以嘗試以下方法:

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