The easiest way to remove the bidirectional recursive relationships?

You can use @Expose(serialize = false) to avoid the Collection to be serialized.


There's a Gson extension called GraphAdapterBuilder that can serialize objects that contain circular references. Here's a very simplified example from the corresponding test case:

Roshambo rock = new Roshambo("ROCK");
Roshambo scissors = new Roshambo("SCISSORS");
Roshambo paper = new Roshambo("PAPER");
rock.beats = scissors;
scissors.beats = paper;
paper.beats = rock;

GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()
    .addType(Roshambo.class)
    .registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(rock));

This prints:

{
  '0x1': {'name': 'ROCK', 'beats': '0x2'},
  '0x2': {'name': 'SCISSORS', 'beats': '0x3'},
  '0x3': {'name': 'PAPER', 'beats': '0x1'}
}

Note that the GraphAdapterBuilder class is not included in gson.jar. If you want to use it, you'll have to copy it into your project manually.


Use transient for ignoring @OneToMany sets for google.gson


I don't know about with Gson but I'm working with Jackson. Look up an example of using its ObjectMapper class. As for the recursion, use @JsonManagedReference and @JsonBackReference to stop that. Look those up for example usage too.