简体   繁体   中英

Parse a pojo into Json with Jersey

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 wich 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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM