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

时间:2019-03-15 08:33:06

标签: 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组成。

1 个答案:

答案 0 :(得分:1)

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不知道该怎么做,而是将树转换为普通的旧地图。

当您要强制使用特定的类型时,仅 class 定义是不够的(有关此here的更多信息)!幸运的是,杰克逊对这个确切的问题有一些方便的功能。 constructCollectionType()使用您选择的特定类型创建一个JavaType(不是JavaClass),在这种情况下,杰克逊知道该怎么做!

侧注:当前,如果不对树进行标记,就无法执行此操作,请参见this github问题。

要使代码更具可读性,可以引入扩展功能:

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