How do I specialize deserializing 'null' with Jackson?-Collection of common programming errors
I have a class that can output any of the following:
- { title: “my claim” }
- { title: “my claim”, judgment: null }
- { title: “my claim”, judgment: “STANDING” }
(notice how judgment is different in each case: it can be undefined, null, or a value)
The class looks like:
class Claim {
String title;
Nullable judgment;
}
and Nullable is this:
class Nullable {
public T value;
}
with a custom serializer:
SimpleModule module = new SimpleModule("NullableSerMod", Version.unknownVersion());
module.addSerializer(Nullable.class, new JsonSerializer() {
@Override
public void serialize(Nullable arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException, JsonProcessingException {
if (arg0 == null)
return;
arg1.writeObject(arg0.value);
}
});
outputMapper.registerModule(module);
Summary: This setup allows me to output the value, or null, or undefined.
Now, my question: How do I write the corresponding deserializer?
I imagine it would look something like this:
SimpleModule module = new SimpleModule("NullableDeserMod", Version.unknownVersion());
module.addDeserializer(Nullable.class, new JsonDeserializer deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
if (next thing is null)
return new Nullable(null);
else
return new Nullable(parser.readValueAs(inner type));
}
});
but I don’t know what to put for “next thing is null” or “inner type”.
Any ideas on how I can do this?
Thanks!
Originally posted 2013-11-09 21:10:17.