第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

反序列化嵌套的 Json 數組

反序列化嵌套的 Json 數組

四季花海 2023-05-24 15:27:18
我有一些 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”不感興趣,只想反序列化“菜肴”。為此,我創(chuàng)建了兩個類: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 而不必映射我不感興趣的字段?
查看完整描述

2 回答

?
SMILET

TA貢獻1796條經驗 獲得超4個贊

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


public class Dish {


@JsonProperty("name")

private String name;


@JsonProperty("details")

private Detail details;


}


查看完整回答
反對 回復 2023-05-24
?
撒科打諢

TA貢獻1934條經驗 獲得超2個贊

你可以試試這個:

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


查看完整回答
反對 回復 2023-05-24
  • 2 回答
  • 0 關注
  • 292 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號