7

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<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!

Verdagon
  • 2,456
  • 3
  • 22
  • 36

1 Answers1

9

Overide the getNullValue() method in deserializer


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


return "" in it

Community
  • 1
  • 1
Red Bit
  • 455
  • 2
  • 6
  • 15