A custom deserializer for this simple model works fine:
static record Person(
String name,
List<Pet> pets) {
}
static record Pet(
String name,
String type) {
}
but a @Jacksonized
Lombok builder version:
@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;
}
fails with:
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
The problem here is that pets
, which is a list of POJOs, is serialized into a string which the custom deserializer unpacks. But, because there's "no String-argument constructor/factory method to deserialize from String value ('[{'Cutesy','cat'}, {'Tootsie','cat'}]')" the deserialize
method is never invoked, sadly.
The custom deserializer is:
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();
}
}
Replacing @Jacksonized
with an explicit JsonDeserialize(using=PersonDeserializer.class)
does work as the record
-based POJO version does; however, I have multiple deserializers which are selected at runtime.
So, I think I'm forced to collapse the deserializers into a single multiplexing deserializer which then does what's needed at runtime...unless one of you has a bright idea?
The serializers & deserializers are registered with the mapper:
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);
}
which is what I was expecting to tweak at runtime.
This looks like a short-coming/bug in Jackson's builder support; it could an issue in Lombok's Jackson support but I haven't found a manual builder pattern that works either so I suspect Lombok is just a victim of Jackson.
Anyone found a workaround?
Here's the driver:
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());
}
Remove the @Jacksonized
annotation:
@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;
}
Explanation
The @Jacksonized
annotation is, unfortunately, prioritized over the explicitly registered custom deserializer so Jackson is trying to use Person.PersonBuilder
for the deserialization instead of
PersonDeserializer
. Seems like a bug in Jackson so I've opened #3901.