当前位置:网站首页>Jackson - how to convert the array string with only one map object to list < map >

Jackson - how to convert the array string with only one map object to list < map >

2022-06-12 05:53:00 Amos-Chen

background

There is a string that looks like this :

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

Want to convert it to List<Map> object , So I wrote :

// json  For the string mentioned above 
List<Map<String, Object>> mapList = new ObjectMapper().convertValue(json, new TypeReference<List<Map<String, Object>>>() {
    });

Error report in execution :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

I checked the reason because : When you switch There is only one object in the array , This is forbidden by default . Need modification jackson Configuration of .

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>>>() {
    
        });

The execution still reports an error :

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"
}]')

A simple translation : Unable to construct LinkedHashMap Example ( Although there is at least one Creator ).

Re reform : No longer use convertValue Method , change to the use of sth. readValue Method , Direct fix .

solve

// json  For the string mentioned above 
//  However, there will be detected exceptions 
List<Map<String, Object>> mapList = new ObjectMapper().readValue(json, new TypeReference<List<Map<String, Object>>>() {
    });
//  Print converted results 
System.out.println(mapList);

Print the results :

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

原网站

版权声明
本文为[Amos-Chen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010614149531.html