我如何专门与杰克逊反序列化'null'?

Ver*_*gon 4 json jackson

我有一个类可以输出以下任何一个:

  • {title:"我的主张"}
  • {title:"我的主张",判决:null}
  • {title:"我的主张",判断:"站立"}

(注意每种情况下判断的不同之处:它可以是未定义的,null或值)

该课程如下:

class Claim {
   String title;
   Nullable<String> judgment;
}
Run Code Online (Sandbox Code Playgroud)

和Nullable是这样的:

class Nullable<T> {
   public T value;
}
Run Code Online (Sandbox Code Playgroud)

使用自定义序列化程序:

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);
Run Code Online (Sandbox Code Playgroud)

简介:此设置允许我输出值,或null 或undefined.

现在,我的问题是:如何编写相应的解串器?

我想它看起来像这样:

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));
   }
});
Run Code Online (Sandbox Code Playgroud)

但我不知道该为"下一件事是空的"或"内部类型"放什么.

有关如何做到这一点的任何想法?

谢谢!

Red*_*Bit 7

在反序列化器中覆盖getNullValue()方法


请参阅如何将JSON null反序列化为NullNode而不是Java null?


在其中返回""