Java to JSON serialization with Jackson PTH and Spring Data MongoDB DBRef generates extra target property
Asked Answered
E

1

5

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"
          }
        }
      ]
    }
  ]
}
Ethban answered 13/2, 2018 at 10:18 Comment(1)
A
10

The Target field is added by Spring Data because it is a lazy collection. So it is like datahandler etc. in Hibernate for JPA.

Option1: To ignore them you just have to add @JsonIgnoreProperties(value = { "target" }) on class level

@Document(collection = "song")
@JsonIgnoreProperties(value = { "target" })
public class Song {
 ...
}

Option2: Make the Collection not lazy

Aleras answered 13/2, 2018 at 12:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.