java - 当映射包含 DTO 列表的对象成功时,为什么映射 DTO 列表会失败?
问题描述
我正在尝试使用 Jackson 和 Kotlin 将 YAML 文档映射到复杂的 DTO 结构,但似乎在某处遇到了误解。
我正在解析的 YAML 文档是
item_names:
- item:
id: hummingbird/items/potion
name: Potion
我在我的系统中将其建模为
data class ItemDto(val id: String)
data class ItemNameDto(val item: ItemDto, val name: String)
data class ItemNamesList(@JsonProperty("item_names") val itemNames: List<ItemNameDto>)
@Test
fun `mvce`() {
val mapper = ObjectMapper(YAMLFactory())
mapper.registerModule(KotlinModule())
val itemNameSource = "item_names:\n" +
" -\n" +
" item:\n" +
" id: hummingbird/items/potion\n" +
" name: Potion\n"
val root = mapper.readTree(itemNameSource)
val listObject: ItemNamesList = mapper.treeToValue(root)
assertEquals("Potion", listObject.itemNames[0].name)
System.out.println("root node to pojo container: $listObject")
val itemNamesNode: JsonNode = root["item_names"]
val list: List<ItemNameDto> = mapper.treeToValue(itemNamesNode)
assertEquals("Potion", list[0].name)
System.out.println("item_names node to list container: $listObject")
}
测试的输出是:
root node to pojo container: ItemNamesList(itemNames=[ItemNameDto(item=ItemDto(id=hummingbird/items/potion), name=Potion)])
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to hummingbird.item.name.ItemName
at hummingbird.item.name.jackson.MapperTests.mvce(MapperTests.kt:103)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
我坚持的是为什么将源映射到 aItemNamesList
工作正常,但是从 映射对象数组root["item_names"]
,我认为应该给 aList<ItemNameDto>
返回一个LinkedHashMap
由LinkedHashMap
s 组成的。
解决方案
TL;DR 答案:
代替
val list: List<ItemNameDto> = mapper.treeToValue(itemNamesNode)
你应该写
val collectionType = mapper.typeFactory.constructCollectionType(List::class.java, ItemNameDto::class.java)
val list: List<ItemNameDto> = mapper.readValue(mapper.treeAsTokens(itemNamesNode), collectionType)
解释
看一下实际的实现treeToValue()
:
inline fun <reified T> ObjectMapper.treeToValue(n: TreeNode): T = treeToValue(n, T::class.java)
T
在你的情况下应该是 aList<ItemNameDto>
但是因为泛型在 JVM 上被删除了(更多关于这个问题),它实际上只是 a List<*>
,所以杰克逊不知道该怎么做,而是在一个普通的旧 Map 中转换树。
当你想强制一个特定的类型时,一个类定义是不够的(更多关于这个here)!幸运的是,杰克逊为这个确切的问题提供了一些方便的功能。constructCollectionType()
使用您选择的特定类型创建一个JavaType
(不是 JavaClass),在这种情况下,杰克逊知道该怎么做!
旁注:目前没有办法在不对树进行标记的情况下执行此操作,请参阅此github 问题。
为了使您的代码更具可读性,您可以引入一个扩展函数:
fun <T : Any> ObjectMapper.constructCollectionType(kClass: KClass<T>): CollectionType? {
return typeFactory.constructCollectionType(List::class.java, kClass.java)
}
推荐阅读
- c++ - 安装 QT 后的新手问题 - 错误:未知类型名称“QApplication”
- android - Android Studio Play Store 模拟器 adb 未经授权
- javascript - 我使用 window.scrollBy() 进行平滑滚动,但它不适用于 Safari
- android - 导入飞镖包
- python - ECS 任务只能从 SQS 队列中选择一条消息
- node.js - 所有嵌套行都未插入到表中
- angular - regForm.reset() 清除表单但也禁用它?
- javascript - 在 react.js 中单击时如何读取按钮中的值字段
- javascript - 当元素的大小减小并应用过渡时,滚动条推到顶部
- java - 使用文件和 json 正文提出请求