Jackson Map、List反序列化异常
2023-03-06

复杂类型(Map、List)反序列化问题

Jackson 将MapList类型序列化后,如果直接反序列化会抛异常,需要使用TypeFactoryconstructParametricType方法

先从内到外依次构造Type,反序列化时指定类型为该Type。

使用方法

先通过 objectMapper.getTypeFactory() 获取TypeFactory,然后调用 constructParametricType方法

// 构造 JavaType
JavaType resultType = objectMapper.getTypeFactory().constructParametricType();
// 反序列化
List<Map<String, Person>> result = mapper.readValue(s, resultType);

他有两种声明

// 参数为从外到内的 类型class 
// 例  HashMap<String,Long> -> constructParametricType(HashMap.class,String.class,Long.class);
public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses) 

// 多层嵌套的类型,由内到外,先构造内层Type
// 例 ArrayList<HashMap<String,Long>> -> constructParametricType(ArrayList.class, innerType);
public JavaType constructParametricType(Class<?> rawType, JavaType... parameterTypes)

List 包 Map

List<Map<String, Person>> result = new ArrayList<>(); // 需要反序列化的类型

//先构造内层innerType -> Map<String, Person>
JavaType innerType = mapper.getTypeFactory().constructParametricType(HashMap.class, String.class, Person.class);

//再构造List<innerType> 
JavaType resultType = mapper.getTypeFactory().constructParametricType(ArrayList.class, innerType);

//反序列化
List<Map<String, Person>> result2 = mapper.readValue(s, resultType);

Map 包 List