Parse a pojo into JSON with Jersey

101 Views Asked by At

I'm trying to convert an object into JSON format but it doesn't work (I get a strange stack overflow exception). It works perfectly from object to XML. I have a simple entity class User and another class with a manyToMany relationship.

@Entity
@XmlRootElement
public class User extends Person {

    @Column(length = 60)
    private String email;

    @Column(name = "PSEUDO", length = 50)
    protected String pseudo;
   
    @ManyToMany(fetch = FetchType.LAZY ,targetEntity = Group.class)
    @OrderBy("group_name ASC")
    protected List<ItGroup> groups = new LinkedList<ItGroup>();

    ...

    getters

}

the related class

@Entity
@Table(name = "groups")
public class Group implements ItGroup, Serializable {

...
    @XmlTransient
    @ManyToMany(fetch = FetchType.LAZY,mappedBy = "groups",targetEntity = User.class)
    @OrderBy("email ASC")
    private List<ItUser> users = new LinkedList<ItUser>();
...

}

I put the @XmlTransient annotations on getters I want to ignore.

Here is a method in my rest service that return an user from his nickname

    @GET
    @Path("{nickname}")
    @Produces({"application/json"})
   // @Produces({"application/xml"})
    public ItUser getUserFromPseudo(@PathParam("nickname") String pseudo){

        ItUser user = this.daoUser.getUserFromPseudo(pseudo);

        return user;
    }

So it works with @Produces({"application/xml"}) not with @Produces({"application/json"})

I'm using Glassfish 5 and the modules are included this way in the parent POM of my application split into different modules. The fact is that I don't even know which implementation of jersey I'm using... I read that moxy was the best and it could read the jaxb annotations.

  <dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>8.0</version>
    <scope>provided</scope>
  </dependency>

How can I fix that problem?

1

There are 1 best solutions below

1
On

Maybe your "strange stack overflow exception" is caused by an infinite recursion with Jackson, like in this post. So @JsonIgnore, @JsonManagedReference or @JsonBackReference could be an option for you.