On Tue, May 3, 2022 at 8:03 AM Aravind Baliga <[email protected]> wrote:
>
> I am using Jackson to serialize my Java POJO classes. In addition to fields,
> I have in Java POJO, I would like to add some additional information in JSON
> I am writing my own custom `CustomClassSerializer`. If I use this class and
> register to `ObjectMapper` then I get the error:
> ```
> Exception in thread "main"
> com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Type id
> handling not implemented for type org.acme.Tiger (by serializer of type
> org.acme.CustomModule$CustomClassSerializer)
> ```
>
> I am unable to understand what might be going wrong here. If I remove the
> custom registered model then everything works perfectly.
Yes. Your custom deserializer is not doing what it needs to do, as per
exception message.
This because:
>
> Can someone please let me know what may be the cause of this issue? I am
> currently using Jackson 2.13.2 latest version dependencies: `jackson-core,
> jackson-databind, jackson-annotations, jackson-datatype-jdk8`:
>
> Following is the sample code:
> ```
> import com.fasterxml.jackson.annotation.JsonInclude;
> import com.fasterxml.jackson.annotation.JsonSubTypes;
> import com.fasterxml.jackson.annotation.JsonTypeInfo;
> import lombok.*;
>
> @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY,
> visible = true, property = "type")
^^^^^^^^
This means that Polymorphic Type Handling is enabled and all
serializers and deserializers need to then support this
handling. Standard Jackson (de)serializers do that.
Your custom serializer has to do the same if (but only if) you use
`@JsonTypeInfo`.
But are you sure you need that?
IYou can check out definition of `JsonSerializer` to see the
additional method you need to implement, which is:
public void serializeWithType(T value, JsonGenerator gen,
SerializerProvider serializers,
TypeSerializer typeSer)
and basically has to add necessary Type Id as part of serialization;
exactly what needs to be done depends on the kind of Type Id to be
added as well as the kind of contents being serialized (JSON Object,
Array or Scalar).
If you go down this route you may want to look for standard Jackson
serializer implementations for guidance: this class:
src/main/java/com/fasterxml/jackson/databind/ser/std/BeanSerializerBase.java
for example implements the method; it is non-trivial but doable.
In general it's good to try to avoid having to define fully
functioning custom serializers if possible, when using more advanced
features like polymorphic handling.
-+ Tatu +-
--
You received this message because you are subscribed to the Google Groups
"jackson-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/jackson-user/CAGrxA24d35bWAVu1pwLTXcg12D1nvww429UbcNGFEYoti-hxpQ%40mail.gmail.com.