Java 到 JSON 使用 Jackson PTH 和 Spring 数据序列化 MongoDB DBRef 生成额外的目标 属性
Java to JSON serialization with Jackson PTH and Spring Data MongoDB DBRef generates extra target property
从 Java 序列化到 JSON 时,Jackson 在使用 Spring 数据 [=33= 时为引用的实体生成额外的 target
属性 ] @DBRef
延迟加载注释和 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 数据添加,因为它是惰性的 collection。所以它就像 Hibernate for JPA 中的数据处理程序等。
选项一:
要忽略它们,您只需在 class 级别
上添加 @JsonIgnoreProperties(value = { "target" })
@Document(collection = "song")
@JsonIgnoreProperties(value = { "target" })
public class Song {
...
}
选项2:
让Collection不懒惰
从 Java 序列化到 JSON 时,Jackson 在使用 Spring 数据 [=33= 时为引用的实体生成额外的 target
属性 ] @DBRef
延迟加载注释和 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 数据添加,因为它是惰性的 collection。所以它就像 Hibernate for JPA 中的数据处理程序等。
选项一: 要忽略它们,您只需在 class 级别
上添加 @JsonIgnoreProperties(value = { "target" })@Document(collection = "song")
@JsonIgnoreProperties(value = { "target" })
public class Song {
...
}
选项2: 让Collection不懒惰