Rickard Öberg
Rickard Öberg

Reputation: 509

How to use custom id serializer with Jackson?

I'm using Jackson 2.1.4 and want to serialize collections of objects that extend an Event class, and where the JSON has to include the class name for polymorphism purposes. I have put a @JsonTypeInfo annotation on Event, but unfortunately I can't use CLASS as strategy, because my object instantiation pattern is "new FooEvent(){{bar=someValue;}}", which will create anonymous inner classes. I want to put in "FooEvent" as the type in JSON, rather than the anonymous inner class.

It seems like what I need is to do this:

@JsonTypeInfo(use= JsonTypeInfo.Id.CUSTOM, include= JsonTypeInfo.As.PROPERTY, property="type")

But how do I register my own custom id serializer that will output the name of the class?

Upvotes: 2

Views: 1212

Answers (1)

Rickard Öberg
Rickard Öberg

Reputation: 509

Figured out how to solve this: basically add a @JsonTypeIdResolver annotation on the same class as has @JsonTypeInfo, then implement a resolver which it can refer to. Here's what mine looks like. It essentially just removes anonymous inner class if present.

Upvotes: 2

Related Questions