I have an external service which I use to query some data. The data will be in one of two formats (first of which is kind of "legacy", but needs to be supported):
{
"foo": "John Smith"
}
or
{
"foo": {
"name": "John Smith",
"bar": "baz"
}
}
which I want to map to the following POJO:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Outer {
private Foo foo;
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Foo {
String name;
String bar;
}
}
Data in the second format (foo
is an object) should be deserialized just like any other POJO, but given data in the first format (foo
is string), to turn it into an instance of Foo
, I want to call new Foo(<foo>, null)
. To do this, I have created a custom deserializer (@JsonComponent
means that this deserializer will be registered with a kinda-global ObjectMapper
by spring via Jackson Module
interface):
@JsonComponent
public class FooDeserializer extends JsonDeserializer<Outer.Foo> {
@Override
public Outer.Foo deserialize(JsonParser parser, DeserializationContext context)
throws IOException {
JsonNode node = parser.getCodec().readTree(parser);
if (node.isTextual()) {
return new Foo(node.asText(), null);
}
return <delegate to next applicable deserializer>;
}
}
I'm having trouble figuring out how to do the "delegate to next applicable deserializer" part, as every solution I've tried (for example parser.getCodec().treeToValue(node, Outer.Foo.class)
) ends up using the same custom deserializer again, causing infinite recursion. Is this even possible?