Jackson ReadValue 不会转换为 List<>

Jackson ReadValue doesn't convert to List<>

我有问题。我使用自定义注释,它采用方法参数并将它们从 json 转换为 pojo。这是示例:

...
MethodParameter param 
// here a parameter from methods, marked with custom annotation
...
JSON_MAPPER.readValue(node, param.getParameterType());

java.util.LinkedHashMap cannot be cast to com.liferay.portal.kernel.util.KeyValuePair

但是当我尝试转换 List<> 时它不起作用。但是下面的代码工作正常

JSON_MAPPER.readValue(node, new TypeReference<List<KeyValuePair>>(){});

我怎样才能弄清楚收入数据的类型?我该怎么办?

我假设你的方法类似于

public List<KeyValuePair> methodName(..) {..}

换句话说,它的 return 类型就是您希望将 JSON 解析为的类型。

我还假设 MethodParameterorg.springframework.core.MethodParameter. You'll notice that MethodParameter#getParameterType() return 和 Class<?>。在这种情况下,它将 return Class 类型的 List 对象。

给定 List.class,Jackson 无法猜测元素类型。因此,它使用默认值 LinkedHashMap

使用 MethodParameter#getGenericParameterType() 方法将 return 一个 Type 对象完全描述 List<KeyValuePair> return 类型。 Jackson 将从中获得足够的类型信息来从 JSON.

构建合适的对象

您需要将 Type 转换为 ObjectMapper#readValue 所期望的 JavaType

mapper.readValue(node, mapper.getTypeFactory().constructType(param.getGenericParameterType()));