自定义反序列化器,记录工作,但@Jacksonized @Builder中断

z9ju0rcb  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(286)

这个简单模型的自定义反序列化器工作正常:

static record Person(
    String name,
    List<Pet> pets) {
}

static record Pet(
    String name,
    String type) {
}

但是@Jacksonized Lombok构建器版本:

@Getter
@Builder
@Jacksonized
static class Person {
    private final String name;
    private final List<Pet> pets;

}

@Getter
@Builder
static class Pet {
    private final String name;
    private final String type;

}

失败:

com.fasterxml.jackson.databind.RuntimeJsonMappingException: Cannot construct instance of `JacksonTest$Pet` (no Creators, like default constructor, exist): no String-argument constructor/factory method to deserialize from String value ('[{'Cutesy','cat'}, {'Tootsie','cat'}]')
 at [Source: (StringReader); line: 2, column: 5] (through reference chain: JacksonTest$Person$PersonBuilder["pets"]->java.util.ArrayList[0])
    at com.fasterxml.jackson.databind.MappingIterator._handleMappingException(MappingIterator.java:416)
    at com.fasterxml.jackson.databind.MappingIterator.next(MappingIterator.java:201)
    at JacksonTest.readPersonFromCsv(JacksonTest.java:99)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:95)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:91)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:60)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `JacksonTest$Pet` (no Creators, like default constructor, exist): no String-argument constructor/factory method to deserialize from String value ('[{'Cutesy','cat'}, {'Tootsie','cat'}]')
 at [Source: (StringReader); line: 2, column: 5] (through reference chain: JacksonTest$Person$PersonBuilder["pets"]->java.util.ArrayList[0])
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1904)
    at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:400)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1349)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromString(StdDeserializer.java:311)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1495)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:197)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:187)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer._deserializeFromArray(CollectionDeserializer.java:355)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:244)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:28)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeSetAndReturn(MethodProperty.java:158)
    at com.fasterxml.jackson.databind.deser.BuilderBasedDeserializer.vanillaDeserialize(BuilderBasedDeserializer.java:293)
    at com.fasterxml.jackson.databind.deser.BuilderBasedDeserializer.deserialize(BuilderBasedDeserializer.java:217)
    at com.fasterxml.jackson.databind.MappingIterator.nextValue(MappingIterator.java:283)
    at com.fasterxml.jackson.databind.MappingIterator.next(MappingIterator.java:199)
    ... 70 more

这里的问题是pets,它是一个POJO列表,被序列化为一个字符串,定制反序列化器将其解包。但是,因为“没有String-argument构造函数/工厂方法从String value('[' Cutesy ',' cat '},' Tootsie ',' cat '}]')反序列化”,deserialize方法永远不会被调用。
自定义反序列化器为:

static class PersonDeserializer extends StdDeserializer<Person> {
    private static final long serialVersionUID = 1L;

    public PersonDeserializer() {
        this(Person.class);
    }

    public PersonDeserializer(Class<Person> type) {
        super(type);
    }

    @Override
    public Person deserialize(JsonParser p, DeserializationContext ctxt)
      throws IOException, JsonProcessingException {
        JsonNode node = p.getCodec().readTree(p);

        String name = node.get("name").asText();
        String petsSerialized = node.get("pets").asText();

        List<Pet> pets = deserialize(petsSerialized);

        //return new Person(name, pets);
        return Person.builder().name(name).pets(pets).build();
    }

    private static List<Pet> deserialize(String serializedPets) {
        return Arrays.stream(serializedPets.replaceAll("^.\\{?|}?.$", "").split("},\s*\\{"))
                .map(inner -> Arrays.stream(inner.replaceAll("^.'?|'?.$", "").split("','")).toList())
                .map(l -> deserialize(l))
                .collect(Collectors.toList());
    }

    private static Pet deserialize(List<String> l) {
        //return new Pet(l.get(0), l.get(1));
        return Pet.builder().name(l.get(0)).type(l.get(1)).build();
    }
}

用显式的JsonDeserialize(using=PersonDeserializer.class)替换@Jacksonized与基于record的POJO版本一样;但是,我有多个反序列化器,它们是在运行时选择的。
所以,我想我不得不把反序列化器折叠成一个单一的多路复用反序列化器,然后在运行时做需要的事情......除非你们中有人有好主意?
序列化器和反序列化器在Map器中注册:

private static CsvMapper _register(CsvMapper mapper) {
    var module = new SimpleModule();

    module.addSerializer(Person.class, new PersonSerializer());
    module.addDeserializer(Person.class, new PersonDeserializer());

    return (CsvMapper)mapper.registerModule(module);
}

这正是我希望在运行时调整的。
这看起来像是Jackson的构建器支持中的一个缺点/错误;这可能是Lombok的Jackson支持中的一个问题,但我还没有找到一个可以工作的手动构建器模式,所以我怀疑Lombok只是Jackson的受害者。
有人找到解决办法了吗?
司机是这样的:

var mapper = _register(new CsvMapper());

String serializedPersons = """
    name,pets
    Ali,"[{'Cutesy','cat'}, {'Tootsie','cat'}]"
    Jan,"[{'Mr. Bubbles','dog'}, {'Lilly','cat'}]"
    Tom,"[{'Fester','dog'}, {'Wednesday','cat'}]"
    Zoe,"[{'Jaeger','dog'}, {'Deira','cat'}]"
    """;

CsvSchema schema = mapper.schemaFor(Person.class).withHeader();

ObjectReader reader = mapper.readerFor(Person.class).with(schema);

MappingIterator<Person> i = reader.readValues(serializedPersons);

while (i.hasNext()) {
    System.out.println("Person: " + i.next());
}
velaa5lx

velaa5lx1#

删除@Jacksonized注解:

@Getter
@Builder
static class Person {
    private final String name;
    private final List<Pet> pets;

}

@Getter
@Builder
static class Pet {
    private final String name;
    private final String type;

}

说明

不幸的是,@Jacksonized注解的优先级高于显式注册的自定义反序列化器,因此Jackson尝试使用Person.PersonBuilder而不是PersonDeserializer进行反序列化。看起来像是Jackson中的一个bug,所以我打开了#3901

相关问题