Java to JSON serialization with Jackson PTH and Sp

2020-04-07 19:37发布

问题:

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"
          }
        }
      ]
    }
  ]
}

回答1:

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