java - 反序列化嵌套 Json 数组

标签 java json jackson deserialization

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

我找到了this方法并尝试了以下方法:

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;

}

关于java - 反序列化嵌套 Json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57426127/

相关文章:

java - 如何在 Spring boot 中从 Controller 覆盖 @JsonIninclude

java - JRE 或 JDK 必须... Java - Eclipse 问题

javascript - 为什么 JSON.parse 的第二个参数叫做 “reviver” ?

java - 如何修复 Jaxb 的 xmlMapper "Multiple fields representing property "PS""问题?

javascript - 找到匹配项时遍历 JSON 对象并更新值的正确方法是什么

javascript - 在 javascript Web 应用程序中本地存储和访问数据的最佳实践是什么?

java - 验证 JSON 字符串

java - HTML 嵌入不适用于 Java Applet

java - 如何通过 Google Endpoints Api 注释声明 200 之后的其他响应?

java - NoSuchMethodError : JobConf. getCredentials()