4

I'm having an issue with serializing @RelationshipEntities to JSON via Spring Data Rest. Whenever I create the @RelationshipEntity, I run into an infinite recursion on serializing the graph to JSON.

Using JSOG to try to render the graph only results in a different, malformed JSON response.

While I can avoid the issue by using @JsonManagedReference, it doesn't solve the problem as I would like to expose the relationship from both nodes.

I've created a simple application that exhibits the issue. It can be found here: https://github.com/cyclomaniac/neo4j-spring-data-rest-cyclic

It implements very basic Team and Player NodeEntities with a single RelationshipEntity, PlayerPosition.

Player:

@NodeEntity
@JsonIdentityInfo(generator= JSOGGenerator.class)
public class Player {

    @GraphId
    @JsonProperty("id")
    private Long id;
    private String name;
    private String number;

    @Relationship(type = "PLAYS_ON")
    private PlayerPosition position;

    ...

Team:

@NodeEntity
@JsonIdentityInfo(generator= JSOGGenerator.class)
public class Team {

    @GraphId
    @JsonProperty("id")
    private Long id;
    private String name;

    @Relationship(type = "PLAYS_ON", direction = Relationship.INCOMING)
    Set<PlayerPosition> teamPlayers;

    ...

PlayerPosition:

@RelationshipEntity(type="PLAYS_ON")
@JsonIdentityInfo(generator= JSOGGenerator.class)
public class PlayerPosition {
    @GraphId
    @JsonProperty("id")
    private Long id;
    private String position;

    @StartNode
    private Player player;


   @EndNode
   private Team team;

   ...

When wired up to a GraphRepository, hitting the /teams endpoint results in the following output with JSOG in place:

{
  "_embedded" : {
    "teams" : [ {
      "@id" : "1",
      "name" : "Cubs",
      "teamPlayers" : [ {
      "@id" : "2",
        "position" : "Catcher",
        "player" : {
          "@id" : "3"

Notice that the JSON ends prematurely. The server throws an exception:

2016-11-04 15:48:03.495  WARN 12287 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to write HTTP message:
 org.springframework.http.converter.HttpMessageNotWritableException: 
 Could not write content: Can not start an object, 
 expecting field name; nested exception is 
 com.fasterxml.jackson.core.JsonGenerationException: 
 Can not start an object, expecting field name

My assumption is that I've chosen a poor way to implement the relationship, though it feels fairly straightforward. I'd appreciate any tips on how I can properly expose this relationship, ideally via Spring Data Rest, from both the Team and Player nodes.

1 Answers1

1

Try to annotate with @JsonIgnore or pair: @JsonBackReference and @JsonManagedReference

vinga
  • 1,912
  • 20
  • 33