Jackson module signature prevents serializers from being added for self-regulation of generic types

I want to add a custom serializer and deserializer for JSR 363 javax.measure.Quantity<Q extends Quantity<Q>> , which basically encapsulates "value" and "block". Creating a serializer ( extends JsonSerializer<Quantity<?>> ) and a deserializer ( extends StdDeserializer<Quantity<?>> ) is very simple.

But they are not easy to register. For deserializers, this is normal; look at the signature:

 SimpleModule.addDeserializer(Class<T> type, JsonDeserializer<? extends T> deser) 

Note that the deserializer allows you to extend the generic type. So I can do this:

 module.addDeserializer(Quantity.class, new MyQuantityJsonDeserializer()); 

But the serializer is another story; look at the signature to register it:

 SimpleModule.addSerializer(Class<? extends T> type, JsonSerializer<T> ser) 

Oh, pain caused by a limited generic type. I can not do it:

 module.addSerializer(Quantity.class, new MyQuantityJsonSerializer()); 

This is because Quantity.class will never give me Class<Quantity<Q extends Quantity<Q>> . And there is no easy throw around this without introducing any arbitrary common variable in the module method and using acrobatic drops. Even this will not work:

 module.addSerializer((Class<Quantity<?>>) Quantity.class, new MyQuantityJsonSerializer()); 

The best I could do was make my serializer class QuantityJsonSerializer<Q extends Quantity<Q>> extends JsonSerializer<Q> , and then register it as a raw type in the module:

 @SuppressWarnings({"rawtypes", "unchecked"}) final JsonSerializer<Quantity> quantitySerializer = (JsonSerializer<Quantity>) new MyQuantityJsonSerializer(); module.addSerializer(Quantity.class, quantitySerializer); 

Wow, how ugly is that? But this is one of those ways that I can find, even to get it to work, and I had to go through more gymnastics to remove the warnings.

Of course, SimpleModule.addSerializer() could be more flexible in its general parameters, similar to SimpleModule.addDeserializer() ?

I am reporting this here because the Jackson project reported reporting bugs here --- and I also ask for better workarounds. Thanks.

+7
java generics jackson jsr363
source share
1 answer

SimpleModule has an overloaded version of addSerializer() :

 public SimpleModule addSerializer(JsonSerializer<?> ser) 

which allows this to work:

 module.addSerializer(new MyQuantityJsonSerializer()); 

while you define your serializer as:

 public class MyQuantityJsonSerializer extends StdSerializer<Quantity<?>> { public MyQuantityJsonSerializer() { // Note: second argument here is ignored. super(Quantity.class, false); } @Override public void serialize(Quantity<?> value, JsonGenerator gen, SerializerProvider serializers) throws IOException { // Serialize value here... } } 
+3
source share

All Articles