1

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(); 
mitjap
  • 495
  • 1
  • 6
  • 14

1 Answers1

0

You could use the JAXB annotations (and configure your json parser to use the JAXB Annotation inspector - which may be the default value). With those annotations , you could add @XmlTransient on the fields you do not want.

willome
  • 3,062
  • 19
  • 32
  • That wouldn't work in my case. I want all fields to be included when I serialize that class (lets call it Foo). But when I serialize a class that has a reference to Foo I want to include only fields that define primary key (and are annotated with @Id) – mitjap Apr 16 '13 at 19:40