简体   繁体   English

使用 jackson 将命名列表反序列化为列表

[英]Deserialize named list with jackson to a list

I want to deserialize json from String.class with this structure:我想使用以下结构从 String.class 反序列化 json:

{"listName": [{"prop":"value"},{"prop":"value"}, ... ] }

to a List<PropVo> , where PropVo contains String prop as a field.List<PropVo> ,其中 PropVo 包含 String prop 作为字段。

  • I don't want to create a wrapper class with List<PropVo>我不想用List<PropVo>创建包装类
  • I don't want to use substring我不想使用子字符串

Is there an option just to deserialize to a list?是否可以选择反序列化为列表?

You can use a type reference to convert that JSON to a Map<String, List<PropVo>> :您可以使用类型引用将该 JSON 转换为Map<String, List<PropVo>>

Map<String, List<PropVo>> m = objectMapper.readValue(string, 
        new TypeReference<Map<String, List<PropVo>>>() {});

Another way is to use readTree另一种方法是使用 readTree

Example:例子:

ObjectMapper om = new ObjectMapper();
JsonNode list = om.readTree(json).path("listName");
List<PropVo> result = Arrays.asList(om.treeToValue(list,PropVo[].class);

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

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