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

ⅰ亾dé卋堺 提交于 2019-12-01 20:18:56

问题


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



来源:https://stackoverflow.com/questions/48764315/java-to-json-serialization-with-jackson-pth-and-spring-data-mongodb-dbref-genera

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!