1

I'm trying to map a YAML document to a complex DTO structure with Jackson and Kotlin, but seem to have run into a misunderstanding somewhere.

The YAML document I'm parsing is

item_names:
  - item:
      id: hummingbird/items/potion
    name: Potion

I'm modeling it in my system as

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")
    }

The output of the test is:

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)

What I'm stuck on is why mapping the source to an ItemNamesList works fine, but mapping the array of objects from root["item_names"], which I think should give a List<ItemNameDto> returns a LinkedHashMap made up of LinkedHashMaps.

Zymus
  • 1,512
  • 1
  • 13
  • 32

1 Answers1

1

TL;DR answer:

Instead of

val list: List<ItemNameDto> = mapper.treeToValue(itemNamesNode)

you should write

val collectionType = mapper.typeFactory.constructCollectionType(List::class.java, ItemNameDto::class.java)
val list: List<ItemNameDto> = mapper.readValue(mapper.treeAsTokens(itemNamesNode), collectionType)

Explanation

Take a look at the actual implementation of treeToValue():

inline fun <reified T> ObjectMapper.treeToValue(n: TreeNode): T = treeToValue(n, T::class.java)

T should be in your case a List<ItemNameDto> but because generics are erased on the JVM (more about that in this question), it is actually only a List<*>, so Jackson does not know what to do and converts the tree in a plain old Map.

When you want to force a specific type, a class definition is not enough (more about this here) ! Luckily Jackson has some handy functions for this exact problem. constructCollectionType() creates a JavaType (not a JavaClass) with a specific type of your choosing, in this case Jackson knows what to do!

Sidenote: There is currently no way to do this without tokenizing the tree, see this github issue.

To make your code more readable you could introduce an extension function:

fun <T : Any> ObjectMapper.constructCollectionType(kClass: KClass<T>): CollectionType? {
  return typeFactory.constructCollectionType(List::class.java, kClass.java)
}
functionaldude
  • 502
  • 3
  • 13
  • 1
    Thanks a lot for the help. I created an extension function found [here](https://gist.github.com/Zymus/b4d3cda1addf12aada277d4a308642fa) based off your answer. – Zymus Mar 15 '19 at 23:04