I would like to serialize class Foo (that can be persisted) into JSON using flexjson (if you know some other library that support required functionality please speak up). I'd like to include depending reference to class Bar and FooBar, but I only need fields that represent primary key (@Id). I know this can be done manually for every persistent class but I'm sure there's a better way.
Here's an example of my class representation:
@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
}
Here's the output that I'm looking for when serializing class Foo:
{
"id":1,
"someField":"someValue",
"bar":1, // or "bar":{"id":1}
"fooBars":[1,2,3,4,5] // or "fooBars":[{"id":1}, {"id":2}, ...]
}
and when serializing class Bar:
{
"id":1,
"irrelevantField":"someValue",
"foos":[1,2,3,4,5] // or "foos":[{"id":1}, {"id":2}, {"id":3}, ...]
}
I found a temporary solution, but I'm still looking for "right/better" solution
new JSONSerializer().include("bar.id", "fooBars.id").exclude("bar.*", "fooBars.*").serialize((Foo)this).toString();