Sathyakumar Seshachalam
Sathyakumar Seshachalam

Reputation: 2053

@JsonTypeInfo has no effect

Using these dependencies

compile "com.fasterxml.jackson.core:jackson-annotations:2.8.8"
compile "org.codehaus.jackson:jackson-mapper-asl:1.9.13"

And then have an abstract class which has @JsonTypeInfo

@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class", visible=true)
public abstract class Event {
...
}

However when I serialize a concrete sub-class there is no @class property in the output

A concrete subclass

public class SpecificEvent extends GatewayEvent {
    private String id;
    ...
}

And code to serialize it.

ObjectMapper mapper = new ObjectMapper();
    mapper.writerWithDefaultPrettyPrinter().writeValue(new FileWriter(new File("build/event.json")), new SpecificEvent("eventId"));

However I find that generated json does not contain a property @class and so the de-serialization also fails.

The generated json is something like.

{
  "id": "eventId"
}

Upvotes: 2

Views: 801

Answers (1)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22254

You are mixing annotations and mapper from very different versions of jackson v1 from codehaus and v2 from fasterxml. Dependencies for using current version of Jackson (recommended) would be:

com.fasterxml.jackson.core:jackson-databind:2.8.8
com.fasterxml.jackson.core:jackson-annotations:2.8.8

(jackson-annotations probably not explicitly needed as jackson-databind depends on it).

Or if you absolutely must use the older version of Jackson:

org.codehaus.jackson:jackson-mapper-asl:1.9.13
org.codehaus.jackson:jackson-core-asl:1.9.13

I tried your @JsonTypeInfo with jackson 2.8.8 and I got (JacksonBinding is the package where my test class is):

{
  "@class" : "JacksonBinding.SpecificEvent",
  "id" : "eventId"
}

Which seems to be what you expect

Upvotes: 1

Related Questions