如何在Jackson中实现自定义引用类型的JSON序列化

Currently I'm using AtomicReference to get a 3-state semantic for fields in my Java-Beans, that are serialized from and to JSON using Jackson. While this works pretty well out-of-the-box it's pretty annoying that AtomicReference doesn't implement hashCode/equals (take away from my question on this was: for the envisioned usage of AtomicReference hashCode/equals are of no meaning) and I need to manually alter hashCode/equals that are normally generated. Thus I wanted to introduce a custom reference type that should - in terms of de-/serialization - be handled just like AtomicReference but implements proper hashCode/equals methods.

I took on how AtomicReference is handled in Jackson. I found AtomicReference(De)Serializer and implemented a custom MyReferenceSerializer extends ReferenceTypeSerializer<MyReference<?>>. But to be used with the @Json(De)Serialize annotations this implementations would need to provide a no-args constructor, which doesn't seem to be possible as the type information needed by ReferenceTypeSerializer is dynamic and depends on the actually wrapped type.

Next I wanted to add the serializer and deserializer to the Jackson ObjectMapper configuration by implementing (De)Serializers and adding them to the SerializerFactory and DeserializerFactory. However ObjectMapper only offers getSerializerFactory().

Then I took a look on how Optional is handled in Jackson and found the Jdk8Module. There serializers and deserializers are added together with a type modifier. Do I need to implement a custom module as well?!

由于要使已生成的hashCode / equals开箱即用,实现所有这些似乎很容易完成,所以我想知道这是否真的是可行的方法,或者是否存在更简单的解决方案具有自定义引用类型。

评论