title: Stackoverflow error occuring when converting Object list to Json string
body: <p>I have a Java RESTapi, where I want to convert a list of my custom Pet object into Json, and display it in an endpoint.</p>
  
  <p>This I what I have so far:</p>
  
  <pre><code>@Path("/allPets")
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response getPetsfromCollection() {
      List&lt;Pet&gt; petList = new ArrayList&lt;&gt;();
      petList.addAll(facade.returnAllPets());
  
      String json = gson.toJson(petList);
  
      //TODO return proper representation object
       return Response.ok().entity(json).build();
  }
  </code></pre>
  
  <p>I'm using the facade pattern where I have a method of adding Java entities to a list as such: </p>
  
  <pre><code>EntityManagerFactory emf = Persistence.createEntityManagerFactory("PetHospitaljpa");
  
  
  public Collection&lt;Pet&gt; returnAllPets (){
  
      EntityManager  em = emf.createEntityManager();
      //vi laver en typed query for at specificere hvilken datatype, 
      // det er vi leder efter, i dette tilfælde er det en Pet
      TypedQuery&lt;Pet&gt; query = em.createNamedQuery("Pet.findAll", Pet.class);
      return query.getResultList();
  }
  </code></pre>
  
  <p>I'm returning a collection in case I want to change the data structure of ArrayList to something else later. </p>
  
  <p>I have tried several workarounds, but I keep getting a stack overflow error.</p>
  
  <p>Iøm aware of the fact, that I need to use DTO's instead, and I have made a custom method to change entities to DTO's as such:</p>
  
  <pre><code>public static DTOPet converttoDTO(Pet entity){
  
     DTOPet dto = new DTOPet();
     dto.setId(entity.getId());
     dto.setName(entity.getName());
     dto.setBirth(entity.getBirth());
     dto.setDeath(entity.getDeath());
     dto.setSpecies(entity.getSpecies());
  
     return dto;
  }
  </code></pre>
  
  <p>I'm not sure if this is good code practice if I there is something else I can do instead to transform a collection of entities into DTO's?</p>
  
  <p>As pointed out. The problem occurs because I have a circular reference.</p>
  
  <p>inside my Pet Entity class:</p>
  
  <pre><code>@ManyToOne
  private Owner ownerId;
  </code></pre>
  
  <p>inside my Owner Entity class:</p>
  
  <pre><code>@OneToMany(mappedBy = "ownerId")
  private Collection&lt;Pet&gt; petCollection;
  </code></pre>
  
  <p>My Pet Class:</p>
  
  <pre><code>    /*
   * To change this license header, choose License Headers in Project Properties.
   * To change this template file, choose Tools | Templates
   * and open the template in the editor.
   */
  package Entities;
  
  import java.io.Serializable;
  import java.util.Collection;
  import java.util.Date;
  import javax.persistence.Basic;
  import javax.persistence.CascadeType;
  import javax.persistence.Column;
  import javax.persistence.Entity;
  import javax.persistence.GeneratedValue;
  import javax.persistence.GenerationType;
  import javax.persistence.Id;
  import javax.persistence.JoinColumn;
  import javax.persistence.ManyToOne;
  import javax.persistence.NamedQueries;
  import javax.persistence.NamedQuery;
  import javax.persistence.OneToMany;
  import javax.persistence.Table;
  import javax.persistence.Temporal;
  import javax.persistence.TemporalType;
  import javax.validation.constraints.NotNull;
  import javax.validation.constraints.Size;
  import javax.xml.bind.annotation.XmlRootElement;
  import javax.xml.bind.annotation.XmlTransient;
  
  /**
   *
   * @author kristoffer
   */
  @Entity
  @Table(name = "pet")
  @XmlRootElement
  @NamedQueries({
      @NamedQuery(name = "Pet.findAll", query = "SELECT p FROM Pet p")
      , @NamedQuery(name = "Pet.findById", query = "SELECT p FROM Pet p WHERE p.id = :id")
      , @NamedQuery(name = "Pet.findByName", query = "SELECT p FROM Pet p WHERE p.name = :name")
      , @NamedQuery(name = "Pet.findByBirth", query = "SELECT p FROM Pet p WHERE p.birth = :birth")
      , @NamedQuery(name = "Pet.findBySpecies", query = "SELECT p FROM Pet p WHERE p.species = :species")
      , @NamedQuery(name = "Pet.findByDeath", query = "SELECT p FROM Pet p WHERE p.death = :death")})
  public class Pet implements Serializable {
  
      private static final long serialVersionUID = 1L;
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Basic(optional = false)
      @Column(name = "id")
      private Integer id;
      @Basic(optional = false)
      @NotNull
      @Size(min = 1, max = 45)
      @Column(name = "name")
      private String name;
      @Basic(optional = false)
      @NotNull
      @Column(name = "birth")
      @Temporal(TemporalType.DATE)
      private Date birth;
      @Basic(optional = false)
      @NotNull
      @Size(min = 1, max = 45)
      @Column(name = "species")
      private String species;
      @Column(name = "death")
      @Temporal(TemporalType.DATE)
      private Date death;
      @OneToMany(cascade = CascadeType.ALL, mappedBy = "petId")
      private Collection&lt;Event&gt; eventCollection;
      @JoinColumn(name = "owner_id", referencedColumnName = "id")
      @ManyToOne
      private Owner ownerId;
  
      public Pet() {
      }
  
      public Pet(Integer id) {
          this.id = id;
      }
  
      public Pet(Integer id, String name, Date birth, String species) {
          this.id = id;
          this.name = name;
          this.birth = birth;
          this.species = species;
      }
  
      public Integer getId() {
          return id;
      }
  
      public void setId(Integer id) {
          this.id = id;
      }
  
      public String getName() {
          return name;
      }
  
      public void setName(String name) {
          this.name = name;
      }
  
      public Date getBirth() {
          return birth;
      }
  
      public void setBirth(Date birth) {
          this.birth = birth;
      }
  
      public String getSpecies() {
          return species;
      }
  
      public void setSpecies(String species) {
          this.species = species;
      }
  
      public Date getDeath() {
          return death;
      }
  
      public void setDeath(Date death) {
          this.death = death;
      }
  
      @XmlTransient
      public Collection&lt;Event&gt; getEventCollection() {
          return eventCollection;
      }
  
      public void setEventCollection(Collection&lt;Event&gt; eventCollection) {
          this.eventCollection = eventCollection;
      }
  
      public Owner getOwnerId() {
          return ownerId;
      }
  
      public void setOwnerId(Owner ownerId) {
          this.ownerId = ownerId;
      }
  
      @Override
      public int hashCode() {
          int hash = 0;
          hash += (id != null ? id.hashCode() : 0);
          return hash;
      }
  
      @Override
      public boolean equals(Object object) {
          // TODO: Warning - this method won't work in the case the id fields are not set
          if (!(object instanceof Pet)) {
              return false;
          }
          Pet other = (Pet) object;
          if ((this.id == null &amp;&amp; other.id != null) || (this.id != null &amp;&amp; !this.id.equals(other.id))) {
              return false;
          }
          return true;
      }
  
      @Override
      public String toString() {
          return "Pet{" + "id=" + id + ", name=" + name + ", birth=" + birth + ", species=" + species + ", death=" + death + ", eventCollection=" + eventCollection + ", ownerId=" + ownerId + '}';
      }   
  }
  </code></pre>
  
  <p>EDIT:
  I tried creating a method, where I convert all the objects to DTO's, but the string is still empty when it is displayed:</p>
  
  <pre><code> @Path("/allPets")
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response getPetsfromCollection() { 
  
      //med denne metode skal vi bruge et DTO(data transfer object til at formatere til Json)
  
      List&lt;Pet&gt; petList = new ArrayList&lt;&gt;();
      List&lt;DTOPet&gt; DTOPetList = new ArrayList&lt;&gt;();
  
      petList.addAll(facade.returnAllPets());
      for(Pet pet: petList){
          DTOPet dtopet = EntitytoDTO.converttoDTO(pet);
          DTOPetList.add(dtopet);
      }
  
      String json = gson2.toJson(DTOPetList);
       return Response.ok().entity(json).build();
  }
  </code></pre>
  
  <p>When I use the debugger, the new list is created successfully, with the right parameters, but the String JSON is just created like this <code>[{},{},{},{}]</code>, even though I use GSON</p>