FasterXML / jackson-databind

General data-binding package for Jackson (2.x): works on streaming API (core) implementation(s)
Apache License 2.0
3.5k stars 1.37k forks source link

override default JsonSerializer #586

Closed herau closed 9 years ago

herau commented 9 years ago

Hello,

I have a class with a default JsonSerializer.

@JsonSerialize(using = WidgetInstanceSerializer.class)
public interface WidgetInstance {}

public class WidgetInstanceSerializer extends JsonSerializer<WidgetInstance> {}

But sometimes i want to serialize this class in another way. so i have another JsonSerializer

public class ContextWidgetInstanceSerializer extends JsonSerializer<WidgetInstance> {}

But when i try to use this serializer, the default serializer is selected instead of my custom serializer

ObjectMapper contextMapper = new ObjectMapper().registerModule(new SimpleModule().addSerializer(WidgetInstance.class, new ContextWidgetInstanceSerializer()));

WidgetInstance widgetInstance = new WidgetInstance([...])

contextMapper.valueToTree(widgetInstance); // WidgetInstanceSerializer is used instead of ContextWidgetInstanceSerializer
cowtowncoder commented 9 years ago

This is how it is supposed to work: class annotations have higher precedence than serializers registered for types.

But you can override annotations by using mix-in annotations.

herau commented 9 years ago

there is no way to have this kind of features (mix-in) but with JsonSerializer ? because JsonSerializer suppose to be more efficient that declare annotations on POJO

cowtowncoder commented 9 years ago

No: priority is well-defined in that more specific (annotations to the property or class) overrides less specific (general by-type registrations). There is no performance difference between mix-in annotations, regular annotations or registration: serializer to use is determined once and cached.

herau commented 9 years ago

In this wiki https://github.com/FasterXML/jackson-docs/wiki/Presentation:-Jackson-Performance, Streaming API should be more efficient than data binding (annotations). So did i loose in performance when i use annotations compared to serializer (streaming API) ? Because my understanding is that only mix-in can solve my problem.

cowtowncoder commented 9 years ago

If you use annotations, you are already using databind, not pure streaming. So there is no difference.

Reference to using Streaming API only means that if you write your own low-level code with direct JsonParser and JsonGenerator calls, it can be even faster than going through automatic handling of properties by JsonSerializer and JsonDeserializer. But all annotations are equal in that they are read once, and used to construct deserializer/serializer; after construction annotations are not checked again during runtime when using same ObjectMapper (different ObjectMappers do have their own caches for (de)serializers, which is how you can use different mix-ins, but only with different mappers).