为什么Kotlin Jackson不能反序列化列表 [英] Why kotlin jackson can't deserialize list
问题描述
我有一个功能:
inline fun <reified T : Any>parse(result: String): T = mapper.readValue<Response<T>>(result).someValue
当我传递列表类型时,例如List<MyClass>
,并尝试从中获取一些物品,出现以下异常:
When I pass a list type, e.g. List<MyClass>
, and try to get some item from it, I get the following exception:
Exception in thread "ForkJoinPool.commonPool-worker-3"
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to MyClass
推荐答案
您需要将类型传递给readValue
-函数,否则Jackson将无法知道应将其转换为哪种类型.默认情况下,杰克逊然后只返回包含键及其值的地图.
You need to pass the type to the readValue
-function, otherwise Jackson has no way to know to which type it should transform to. By default jackson then just returns a map with keys and its values.
因此,对于您的特定问题,您可以制作parse
-function
inline
并在传递的类型中添加reified
.这样可以确保将实际类型也传递给Jackson.另请参阅科特林参考资料中的已修改类型.另外,您可以传递实际类型(使用TypeReference
或使用类本身(如果不是通用的)).
So for your particular problem you may just make the parse
-function
inline
and add a reified
to your passed type. This ensures, that the actual type is also passed to Jackson. See also reified types in the kotlin reference. Alternatively you pass the actual type (either using TypeReference
or the class itself if it's not generic).
以前,此答案还包含有关如何将json列表反序列化为实际列表的一般信息,在此我将留作参考:
Previously this answer also contained a general information how to deserialize a json list to an actual one, which I will leave here for reference:
mapper.readValue(result, object : TypeReference<List<MyClass>>() {})
,或者如果您使用 jackson-module-kotlin :
mapper.readValue<List<MyClass>>(result)
应用于您的函数,如下所示:
Applied to your function that could look like the following:
inline fun <reified T : Any>parse(result: String): T = mapper.readValue(result, object : TypeReference<T>() {})
或使用jackson-module-kotlin:
or using jackson-module-kotlin:
inline fun <reified T : Any>parse(result: String): T = mapper.readValue(result)
调用它就是:
val yourObjList = parse<List<MyClass>>(yourJson)
// or
val yourObjList : List<MyClass> = parse(yourJson)
请注意,我使用了reified
(这意味着inline
).如果不使用reified
,则实际类型不会传递给jackson-module-kotlin的方法化.
Note that I used reified
(which implies inline
). If you do not use reified
the actual type is not passed on to jackson-module-kotlin's reified methods.
这篇关于为什么Kotlin Jackson不能反序列化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!