【问题标题】:Deserialize nested Json Arrays反序列化嵌套的 Json 数组
【发布时间】:2019-12-16 23:07:36
【问题描述】:

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

但是,如果我运行它,我会得到 ​​p>

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,而不必映射我不感兴趣的字段?

【问题讨论】:

    标签: java json jackson deserialization


    【解决方案1】:

    您应该将 details 映射为 POJO 而不是 List&lt;Details&gt;

    public class Dish {
    
    @JsonProperty("name")
    private String name;
    
    @JsonProperty("details")
    private Detail details;
    
    }
    

    【讨论】:

      【解决方案2】:

      你可以试试这个:

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

      【讨论】:

        猜你喜欢
        • 2019-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多