杰克逊的ObjectMapper.readValue()

时间:2018-10-16 09:57:43

标签: kotlin jackson

嗨,我正在尝试Kotlin,通常我可以在Java中使用ObjectMapper。我想做的是存储一些包含键绑定数据及其应包含的数据的键绑定数组。按下CTRL + SHIFT + X组合键应该“退出”,但是在Kotlin中,我似乎得到了:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "binds" (class Overlay.KeyBinds$Companion), not marked as ignorable (0 known properties: ])
at [Source: (File); line: 1, column: 11] (through reference chain: Overlay.KeyBinds$Companion["binds"])

at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:60)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:822)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1152)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1589)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1567)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:294)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2902)
at Overlay.KeyBinds$Companion.importer(KeyBinds.kt:51)
at Overlay.KeyBindIOTest.importer(KeyBindIOTest.java:45)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
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)

应该由测试生成的keybinds文件似乎产生了我希望它产生的输出:

{"binds":[{"keyState":{"shiftHeld":true,"ctrlHeld":false,"altHeld":false,"key":30},"function":"EXIT"},{"keyState":{"shiftHeld":false,"ctrlHeld":false,"altHeld":false,"key":1},"function":"OPEN"}]}

所以,我不确定为什么从文件中导入对象失败,有人知道吗?

我的Kotlin代码:

data class KeyBind(var keyState: KeyState, var function: String)

data class KeyBinds(var binds: Array<KeyBind>)
{
override fun equals(other: Any?): Boolean
{
    if (this === other) return true
    if (javaClass != other?.javaClass) return false

    other as KeyBinds

    if (!Arrays.equals(binds, other.binds)) return false

    return true
}

override fun hashCode(): Int
{
    return Arrays.hashCode(binds)
}

fun exporter(location: String)
{
    var kb_file = File(location)

    if (kb_file.exists())
        kb_file.delete()

    var objectMapper = ObjectMapper()
    objectMapper.writeValue(kb_file, this)
}

companion object
{
    fun importer(location: String): Companion?
    {
        var kb_file = File(location)

        if (kb_file.exists())
        {
            var objectMapper = ObjectMapper()
            return objectMapper.readValue(kb_file, KeyBinds.javaClass)

        }
        return null
    }
}
}

我的JUnit测试:

public class KeyBindIOTest
{
private KeyBinds keyBinds = new KeyBinds(new KeyBind[]
{
        new KeyBind(new KeyState(true, false, false, 30), "EXIT"),
        new KeyBind(new KeyState(false, false, false, 1), "OPEN")
});
static final String TEST_LOCATION = System.getenv("LOCALAPPDATA") + File.separator + "TEST" + File.separator + "keybinds";

@Before
public void before()
{
    // Create Test Dir if it doesn't exist.
    File f = new File(System.getenv("LOCALAPPDATA") + File.separator + "TEST");
    if (!f.exists())
        f.mkdir();
}

@Test
public void exporter()
{
    keyBinds.exporter(TEST_LOCATION);

    // Verify file was created
    File f = new File(TEST_LOCATION);
    assertTrue(f.exists());
}

@Test
public void importer()
{
    assertEquals(keyBinds, KeyBinds.Companion.importer(TEST_LOCATION));
}

更新: 我通过更改解决了该特定错误:

return objectMapper.readValue(kb_file, KeyBinds.javaClass)

收件人:

 return objectMapper.readValue(kb_file, KeyBinds::class.java)

使用.javaClass似乎会告诉ObjectMapper该类是Companion,而不是您想要的类。

不幸的是,这还不是错误的终点,而我最终遇到了:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `Overlay.KeyBinds` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (File); line: 1, column: 2]

at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1451)
at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1027)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1297)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2902)
at Overlay.KeyBinds$Companion.importer(KeyBinds.kt:53)
at Overlay.KeyBindTest.importer(KeyBindTest.java:44)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
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)

1 个答案:

答案 0 :(得分:0)

我通过更改来解决此特定错误:

return objectMapper.readValue(kb_file, KeyBinds.javaClass)

收件人:

return objectMapper.readValue(kb_file, KeyBinds::class.java)

使用.javaClass似乎会告诉ObjectMapper该类是Companion,而不是我想要的。

我收到的第二个错误是通过以下方式解决的:

Jackson, deserialize class with private fields and arg-constructor without annotations