Amos的随笔

Java/Python/Go,软件测试等等

导航

jackson - 只有一个 Map 对象的数组字符串怎么转为 List<Map>

背景

有一个字符串长得像下面这个样子:

[{
    "success": {
        "description": "Welcome to JSON Viewer",
        "code": 200
    },
    "message": "this is a message"
}]

想将其转化为 List<Map>对象,于是乎我这么写:

// json 为上面提到的字符串
List<Map<String, Object>> mapList = new ObjectMapper().convertValue(json, new TypeReference<List<Map<String, Object>>>() {});

执行报错:Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of ‘java.util.ArrayList<java.util.Map<java.lang.String,java.lang.Object>>’ out of VALUE_STRING token

查了一下原因是因为:转换的时候数组里面只有一个对象,而这样是被默认禁止的。需要修改 jackson 的配置。

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
List<Map<String, Object>> mapList = mapper.convertValue(json, new TypeReference<List<Map<String, Object>>>() {
        });

执行依然报错:

Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `java.util.LinkedHashMap` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('[{
    "success": {
        "description": "Welcome to JSON Viewer",
        "code": 200
    },
    "message": "this is a message"
}]')

简单翻译一下:无法构造LinkedHashMap的实例(尽管至少存在一个创建者)。

再改:不再使用convertValue方法,改用readValue方法,直接搞定。

解决

// json 为上面提到的字符串
// 不过会有受检异常
List<Map<String, Object>> mapList = new ObjectMapper().readValue(json, new TypeReference<List<Map<String, Object>>>() {});
// 打印转换后的结果
System.out.println(mapList);

打印结果:

[{success={description=Welcome to JSON Viewer, code=200}, message=this is a message}]

posted on 2021-01-01 16:57  AmosChen  阅读(42)  评论(0编辑  收藏  举报  来源