从Java序列化为JSON时,target
当使用@DBRef
带有延迟加载和Jackson的多态类型处理的Spring Data MongoDB 批注时,Jackson会为引用的实体生成一个额外的属性。为什么会发生这种情况,并且可以省略多余的target
属性?
代码示例
@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等。
选项1:要忽略它们,您只需要在类级别添加@JsonIgnoreProperties(value = {“ target”})
@Document(collection = "song")
@JsonIgnoreProperties(value = { "target" })
public class Song {
...
}
选项2:使集合不懒惰
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句