我想使用 flexjson 将 Foo 类(可以持久化)序列化为 JSON(如果您知道其他支持所需功能的库,请说出来)。我想包括对类 Bar 和 FooBar 的依赖引用,但我只需要表示主键 (@Id) 的字段。我知道这可以为每个持久类手动完成,但我确信有更好的方法。
这是我的类(class)表示的示例:
@Entity
public class Foo {
@Id @GeneratedValue(...)
private Long id;
private String someField;
@ManyToOne
private Bar bar;
@OneToMany
private Collection<FooBar> fooBars
}
@Entity
public class Bar {
@Id @GeneratedValue(...)
private long id;
private String irrelevantField
@OneToMany
private Collection<Foo> foos;
}
@Entity
public class FooBar {
@Id @GeneratedValue(...)
private Long id;
private String irrelevantField
}
这是我在序列化类 Foo 时寻找的输出:
{
"id":1,
"someField":"someValue",
"bar":1, // or "bar":{"id":1}
"fooBars":[1,2,3,4,5] // or "fooBars":[{"id":1}, {"id":2}, ...]
}
当序列化 Bar 类时:
{
"id":1,
"irrelevantField":"someValue",
"foos":[1,2,3,4,5] // or "foos":[{"id":1}, {"id":2}, {"id":3}, ...]
}
我找到了一个临时解决方案,但我仍在寻找“正确/更好”的解决方案
new JSONSerializer().include("bar.id", "fooBars.id").exclude("bar.*", "fooBars.*").serialize((Foo)this).toString();
最佳答案
您可以使用 JAXB
注释(并将 json 解析器配置为使用 JAXB 注释检查器 - 这可能是默认值)。通过这些注释,您可以在不需要的字段上添加 @XmlTransient
。
关于java - 如何仅使用主键将引用的持久类序列化为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16034455/