How do I specialize in null deserialization with Jackson?

I have a class that can output any of the following:

  • {title: "my requirement"}
  • {title: "my requirement", solution: null}
  • {title: "my requirement", solution: "STANDING"}

(note that in each case the judgment is different: it can be undefined, null or value)

The class is as follows:

class Claim { String title; Nullable<String> judgment; } 

and nullable:

 class Nullable<T> { public T value; } 

using a special 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 setting allows me to output a value, either null, or undefined.

Now, my question is : How to write an appropriate deserializer?

I assume it will 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 “the next thing is zero” or “inner type”.

Any ideas on how I can do this?

Thanks!

+4
source share
1 answer

On top of the getNullValue () method in the deserializer


see How to deserialize JSON null to NullNode instead of Java null?


return "" in it

+5
source

All Articles