Why does Jackson think this object is a subtype (when it's really not)?

Viewed 4935

I have a relatively simple schema. I have a Subscription object that holds a reference to a User. On the flip side, I have a User object that has reference to an array of Subscriptions.

The problem is that when Jackson tries to deserialize a User JSON payload that contains a Subscription array, it throws an InvalidTypeIdException claiming that Subscription couldn't be resolved as a subtype of User. Why? Because Subscription is NOT a subtype of User.

The User schema is as follows:

public class User extends Base {

  private List<Subscription> subscriptions;

  // other props & getters/setters
}

The Subscription schema is:

public class Subscription extends Base {

  private User user;

  // other props & getters/setters
}

Both classes have getters and setters defined. For context, here is the Base class schema. Note that we have it annotated with @JsonTypeInfo:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "model-type", visible = true)
public abstract class Base {
    protected String id;
}

The specific exception that is thrown is:

Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'Subscription' into a subtype of [simple type, class com.random.package.viewmodel.User]: known type ids = [User]
 at [Source: java.io.PushbackInputStream@5c86366e; line: 17, column: 5] (through reference chain: com.random.package.viewmodel.User["subscriptions"]->java.util.ArrayList[0])

So why is this happening? I know that @JsonTypeInfo is playing a part, but it is needed for other parts of our model schema. Is it something to do with my Base class?

I was thinking this might be happening due to the bi-directionality between these two entities. So I tried adding @JsonManagedReference, @JsonBackReference, and @JsonIgnore to the subscriptions field in User without any success.

So how can I make Jackson play nice with these two types?

For further reference here is the serialized JSON this is occurring on:

{
  "model-type": "User",
  "id": "peppermint-patty",
  "stub": false,
  "email": "random@randomemail.com",
  "username": "Peppermint Patty",
  "schema-version": "v1",
  "first-name": "Peppermint",
  "last-name": "Patty",
  "subscriptions": [
    {
      "id": "da73402f-9258-4284-a80a-5a050b4e721d",
      "schema-version": "v1",
      "model-type": "Subscription"    
    }
  ]
} 
0 Answers
Related