I have a class that can output any of the following:
(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<String> judgment;
}
and Nullable is this:
class Nullable<T> {
public T value;
}
with a custom serializer:
SimpleModule module = new SimpleModule("NullableSerMod", Version.unknownVersion());
module.addSerializer(Nullable.class, new JsonSerializer<Nullable>() {
@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<Nullable<?>>() {
@Override
public Nullable<?> 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!
With its default settings, Jackson serializes null-valued public fields. In other words, resulting JSON will include null fields. Here, the name field which is null is in the resulting JSON string.
You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.
Jackson default include null fields 1.2 By default, Jackson will include the null fields. To ignore the null fields, put @JsonInclude on class level or field level.
Jackson uses default (no argument) constructor to create object and then sets value using setters. so you only need @NoArgsConstructor and @Setter.
Overide the getNullValue() method in deserializer
see How to deserialize JSON null to a NullNode instead of Java null?
return "" in it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With