I have a Jackson Question.
Is there a way to deserialize a property that may have two types, for some objects it appears like this
\"someObj\" : { \"
Edit: Since Jackson 2.5.0, you can use DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_EMPTY_OBJECT to resolve your problem.
The solution Bruce provides has a few problems/disadvantages:
Here is my "generic" solution for that problem:
public abstract class EmptyArrayAsNullDeserializer extends JsonDeserializer {
private final Class clazz;
protected EmptyArrayAsNullDeserializer(Class clazz) {
this.clazz = clazz;
}
@Override
public T deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
if (node.isArray() && !node.getElements().hasNext()) {
return null;
}
return oc.treeToValue(node, clazz);
}
}
then you still need to create a custom deserializer for each different type, but that's a lot easier to write and you don't duplicate any logic:
public class Thing2Deserializer extends EmptyArrayAsNullDeserializer {
public Thing2Deserializer() {
super(Thing2.class);
}
}
then you use it as usual:
@JsonDeserialize(using = Thing2Deserializer.class)
If you find a way to get rid of that last step, i.e. implementing 1 custom deserializer per type, I'm all ears ;)