如何在使用JAX-RS时返回JSON中的对象列表

时间:2013-05-07 01:08:53

标签: json jboss7.x resteasy

我有工作......有点儿。除了打印出Json之外,它会打印出许多重复的代码。我怀疑这与它的编组方式有关。无论如何,这是我的代码:

User.java

@XmlRootElement(name="user")

@Entity
@Table(name="users")
public class User implements Serializable{
    private static final long serialVersionUID = 1L;

    @XmlElement(required=true)
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    @XmlElement(required=true)
    @Column(name="username", nullable=false)
    private String userName;

    @XmlElement(required=true)
    @Column(name="phoneid", nullable=false)
    private String phoneid;

    @XmlTransient
    @ManyToMany(
        cascade={CascadeType.ALL},
        mappedBy="voters",
        targetEntity=Vote.class,
        fetch=FetchType.EAGER

    )
    private List<Vote> votes = new ArrayList<Vote>();

Vote.java

@XmlRootElement(name="vote")
@Entity
@Table(name="votes")
public class Vote implements Serializable {
    private static final long serialVersionUID = 1L;

    @XmlElement(required=true)
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id", nullable=false)
    private int id;

    @XmlElement(required=true)
    @Column(name="name", nullable=false)
    private String name;

    @XmlElement(required=true)
    @Column(name="max", nullable=false)
    private int max;

    @XmlElement(required=true)
    @Column(name="current", nullable=false)
    private int current;

    @XmlElement(required=true)
    @Column(name="is_simple", nullable=false)
    private int isSimple;

    @XmlTransient
    @ManyToMany(cascade = {CascadeType.ALL}, targetEntity=User.class, fetch=FetchType.EAGER)
    @JoinTable(name = "vote_user",
            joinColumns = {@JoinColumn(name = "vote_id")},
            inverseJoinColumns = {@JoinColumn(name = "user_id")}
    )
    private List<User> voters = new ArrayList<User>();

GetRestfulVote.java

@Path("/votes")
public class GetRestfulVote {
    @EJB
    VoteBeanInterface bean;

    @GET
    @Path("/{userid}")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Vote> getVotesJson(@PathParam("userid") String userId) {
        //Will be getting using the user id to be able to set a flag if the calling user voted in it
        List<Vote> listOfVotes = bean.getVotes();

        return listOfVotes;
    }

}

现在从我的代码中可以明显看出,我的VoteUser类之间有很多关系。我相信问题出在哪里。但问题是我不知道如何防止它从“jsonification”过程中被忽略。更重要的是,我如何强制它只将拥有类列表(Votes)转换为Json。任何帮助和澄清将不胜感激!

0 个答案:

没有答案