使用Jackson PTH和Spring Data MongoDB DBRef的Java到JSON序列化生成额外的目标属性 [英] Java to JSON serialization with Jackson PTH and Spring Data MongoDB DBRef generates extra target property

查看:58
本文介绍了使用Jackson PTH和Spring Data MongoDB DBRef的Java到JSON序列化生成额外的目标属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Java序列化为JSON时,当使用带有延迟加载和Jackson的多态类型处理的Spring Data MongoDB @DBRef批注时,Jackson会为引用的实体生成一个额外的target属性.为什么会发生这种情况,并且可以省略多余的target属性?

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?

代码示例

@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;
}

生成的JSON

{
  "id": "someId1",
  "products": [
    {
      "id": "someId2",
      "songs": [
        {
        "id": "someId3",
        "title": "Some title",
        "target": {
          "id": "someId3",
          "title": "Some title"
          }
        }
      ]
    }
  ]
}

推荐答案

目标"字段由Spring Data添加,因为它是一个惰性集合.因此就像Hibernate for JPA中的datahandler等.

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

选项1: 要忽略它们,您只需要在类级别添加@JsonIgnoreProperties(value = {"target"})

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

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

选项2: 使收藏集不偷懒

Option2: Make the Collection not lazy

这篇关于使用Jackson PTH和Spring Data MongoDB DBRef的Java到JSON序列化生成额外的目标属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆