When serializing from Java to JSON, Jackson generates an extra target
property for referenced entities when using the Spring Data MongoDB @DBRef
annotation with lazy loading and Jackson’s polymorphic type handling. Why does this occur, and is it possible to omit the extra target
property?
Code Example
@Document(collection = "cdBox")
public class CDBox {
@Id
public String id;
@DBRef(lazy = true)
public List<Product> products;
}
@Document(collection = "album")
public class Album extends Product {
@DBRef(lazy = true)
public List<Song> songs;
}
@Document(collection = "single")
public class Single extends Product {
@DBRef(lazy = true)
public List<Song> songs;
}
@Document(collection = "song")
public class Song {
@Id
public String id;
public String title;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
property = "productType",
include = JsonTypeInfo.As.EXTERNAL_PROPERTY)
@JsonSubTypes(value = {
@JsonSubTypes.Type(value = Single.class),
@JsonSubTypes.Type(value = Album.class)
})
public abstract class Product {
@Id
public String id;
}
Generated JSON
{
"id": "someId1",
"products": [
{
"id": "someId2",
"songs": [
{
"id": "someId3",
"title": "Some title",
"target": {
"id": "someId3",
"title": "Some title"
}
}
]
}
]
}