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

时间:2013-04-13 00:48:31

标签: json jackson

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

  • {title:“my claim”}
  • {title:“我的主张”,判决:null}
  • {title:“my claim”,判决:“STANDING”}

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

该课程如下:

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

和Nullable是这样的:

class Nullable<T> {
   public T value;
}

使用自定义序列化程序:

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);

摘要:此设置允许我输出值,或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));
   }
});

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

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

谢谢!

1 个答案:

答案 0 :(得分:7)

覆盖反序列化器中的getCellValue()方法


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

返回“”在其中