我正在尝试使用杰克逊反序列化地图
//. ObjectMapper initialization
public static final ObjectMapper objectMapper = JsonMapper.builder()
.addModule(new JavaTimeModule())
.addModule(new SimpleModule()
.addAbstractTypeMapping(Claims.class, DefaultClaims.class)
.addAbstractTypeMapping(GrantedAuthority.class, SimpleGrantedAuthority.class)
)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.addMixIn(PersonTraits.class, PersonTraitsMixIn.class)
.addMixIn(SimpleGrantedAuthority.class, SimpleGrantedAuthorityMixin.class)
.build();
反序列化方法:
`public static <K, V, T extends Map<?, ?>> Map<K, List<V>> deserializeMap(String` genericObject, Class<T> mapClass,
Class<K> keyClass, Class<List<V>> valueClass) throws Exception {
if (genericObject == null) {
return null;
}
try {
return objectMapper.readValue(genericObject, objectMapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass));
} catch (JsonProcessingException e) {
//. Do something
throw e;
}
}
JUnit 测试用例:
@Test
public void testDeserializeMapContainingListAsValue() throws Exception {
// given
Map<Long, List<Long>> mapToSerialize = new HashMap<>();
List<Long> valueList = new ArrayList<>();
valueList.add(2L);
mapToSerialize.put(1L, valueList);
String serializedMap = SerializationUtil.serializeObject(mapToSerialize);
// when
final Map<Long, List<Long>> result = SerializationUtil.deserializeMap(serializedMap, HashMap.class, Long.class,
List.class);
// then
assertNotNull(result);
}
The when statement is throwing the error:
// when
final Map<Long, List<Long>> result = SerializationUtil.deserializeMap(serializedMap1, HashMap.class, Long.class,
List.class);
The error says:
Required type. Provided
mapClass: Class<T>. Class<HashMap>
keyClass: Class<K> Class<Long>
valueClass: Class<List<V>>. Class<List>
reason: Incompatible equality constraint: List<V> and List
有谁知道发生了什么事以及如何解决它?如果上面的代码中存在我遗漏的明显问题,我深表歉意。我对编程相当陌生。任何帮助将不胜感激。 谢谢大家,保重!
你可能需要做类似的事情
JavaType keyType = typeFactory.constructType(Long.class);
JavaType valueType = typeFactory.constructType(new TypeReference<List<Long>>() {});
return objectMapper.readValue(genericObject, objectMapper.getTypeFactory().constructMapType(mapClass, keyType, valueType));