无法从START_ARRAY令牌中反序列化 java.util.HashMap 的实例

2022-09-01 15:22:27

我在使用jackson-core-2.7.3解析JSON时遇到问题.jar您可以从这里获取它们 http://repo1.maven.org/maven2/com/fasterxml/jackson/core/

我的 JSON 文件是

[
    {
        "Name":  "System Idle Process",
        "CreationDate":  "20160409121836.675345+330"
    },
    {
        "Name":  "System",
        "CreationDate":  "20160409121836.675345+330"
    },
    {
        "Name":  "smss.exe",
        "CreationDate":  "20160409121836.684966+330"
    }
]

而Java代码是我试图解析的,这是

byte[] mapData = Files.readAllBytes(Paths.get("process.txt"));
Map<String,String> myMap = new HashMap<String, String>();
ObjectMapper objectMapper=new ObjectMapper();
myMap = objectMapper.readValue(mapData, HashMap.class);
System.out.println("Map is: "+myMap);

但是在执行时,我得到了错误

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.HashMap out of START_ARRAY token
 at [Source: [B@34ce8af7; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:216)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:873)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:869)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromEmpty(StdDeserializer.java:874)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:337)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3789)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2872)

我尝试在堆栈溢出上搜索,但找不到与此类JSON匹配的解决方案。

任何帮助将不胜感激。

注意:这里提到的是不同的 a 不带 ,对于第一个元素,它直接具有值,并且在该值内具有对。我不确定如何访问值内的对。JSONJSONKeykey:valuekey:value


答案 1

引发此异常的原因是您尝试反序列化 Map 中的列表

解决方案是创建一个类型引用:List<Map<String, Object>>

List<Map<String, Object>> myObjects = 
          mapper.readValue(mapData , new TypeReference<List<Map<String, Object>>>(){});

答案 2

创建一个简单的类优先pojo

class MyClass
{
@JsonProperty
private String Name;
@JsonProperty
private String CreationDate;
}

并使用此代码...

byte[] mapData = Files.readAllBytes(Paths.get("process.txt"));

ObjectMapper objectMapper=new ObjectMapper();
//add this line  
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);    
List<MyClass> myObjects = mapper.readValue(mapData , new TypeReference<List<MyClass>>(){});

byte[] mapData = Files.readAllBytes(Paths.get("process.txt"));

ObjectMapper objectMapper=new ObjectMapper();
 //add this line  
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);    

List<MyClass> myObjects = mapper.readValue(mapData , mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));

myObjects将包含 的 。现在,您可以根据需要访问此列表。ListMyClass