Given json:
{
"name" : {}
}
I would like to parse it into the following Java object using com.fasterxml.jackson
:
class MyClass {
private String name;
}
If you try it, you will get:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token
Is there any way to configure the jackson deserializer (globally for best) it can handle these empty objects
as nulls
without changing the attribute type (from String)?
To do that you can write your own deserializer. Following this you extend the StdDeserializer and register it in the class.
Author edit:
I have used following deserializer for strings and it's working fine, thanks:
public class EmptyObjectDeserializer extends StdDeserializer<String> {
public EmptyObjectDeserializer() {
this(null);
}
public EmptyObjectDeserializer(Class<?> vc) {
super(vc);
}
@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
return node.asText("");
}
}