java - 当映射包含 DTO 列表的对象成功时,为什么映射 DTO 列表会失败?

标签 java kotlin jackson

我正在尝试使用 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)

我所困惑的是为什么将源映射到 ItemNamesList工作正常,但映射来自 root["item_names"] 的对象数组,我认为应该给出 List<ItemNameDto>返回 LinkedHashMapLinkedHashMap 组成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在你的情况下应该是 List<ItemNameDto>但因为泛型在 JVM 上被删除(更多关于 this 问题),它实际上只是一个 List<*> ,所以 jackson 不知道该怎么做,并将树转换为普通的旧 map 。

当您想要强制使用特定的类型时,定义是不够的(更多关于此here)!幸运的是 Jackson 有一些方便的函数来解决这个问题。 constructCollectionType()创建 JavaType (不是 JavaClass)与您选择的特定类型,在这种情况下 Jackson 知道该怎么做!

旁注:目前没有办法在不标记树的情况下做到这一点,请参阅 this github 问题。

为了使代码更具可读性,您可以引入扩展函数:

fun <T : Any> ObjectMapper.constructCollectionType(kClass: KClass<T>): CollectionType? {
  return typeFactory.constructCollectionType(List::class.java, kClass.java)
}

关于java - 当映射包含 DTO 列表的对象成功时,为什么映射 DTO 列表会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55178487/

相关文章:

java - 将现有的 jni 库(已编译 ".so")添加到另一个 android studio 项目

java - 如何按原样发送字节数,而不是将它们作为 Android 蓝牙输出流中的单独数字发送?

java - Google Play 开发者 API - 400 无效值 - InAppPurchases

java - 如何访问 JsonPropertyOrder

java - java中将json字符串反序列化为string对象

java - JAX-RS 和 java.time.LocalDate 作为输入参数

java - Gradle 项目不会从其他项目或 javax.persistence 中导入类

尝试迭代字符串时出现 java.lang.StringIndexOutOfBoundsException

java - JFrame Action 监听器 - 错误

android - Android按钮-聆听者的差异