我使用Gson库将Java对象转换为Json响应...
问题是,在JPA请求之后,由于与其他实体(see my previous question)的递归关系,无法转换从数据库检索的对象,例如:

public class Gps implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "IMEI", nullable = false, length = 20)
    private String imei;
    //some code here...
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "gpsImei", fetch = FetchType.LAZY)
    private List<Coordonnees> coordonneesList;


public class Coordonnees implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "IDCOORDONNEES", nullable = false)
    private Integer idcoordonnees;
    //some code here...
    @JoinColumn(name = "GPS_IMEI", referencedColumnName = "IMEI", nullable = false)
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    private Gps gpsImei;

我的源代码:
  EntityManagerFactory emf=Persistence.createEntityManagerFactory("JavaApplication21PU");
  GpsJpaController gjc=new GpsJpaController(emf);

  Gps gps=gjc.findGps("123456789012345");

  for(int i=0;i<gps.getCoordonneesList().size();i++){
   gps.getCoordonneesList().get(i).setGpsImei(null);
  }

  Gson gson=new Gson();
  String json=gson.toJson(gps);//convert to json response

  System.out.println(json);

如您在这里看到的,我做了:
   for(int i=0;i<gps.getCoordonneesList().size();i++){
     gps.getCoordonneesList().get(i).setGpsImei(null);
   }

仅通过为coordonneesList中的每个GPS对象设置null来消除递归关系。

您认为这是一个很好的解决方案,或者还有其他更实用的方法吗?
谢谢

最佳答案

有一个名为GraphAdapterBuilder的Gson扩展,可以扩展包含循环引用的对象。这是来自相应测试用例的非常简化的示例:

Roshambo rock = new Roshambo("ROCK");
Roshambo scissors = new Roshambo("SCISSORS");
Roshambo paper = new Roshambo("PAPER");
rock.beats = scissors;
scissors.beats = paper;
paper.beats = rock;

GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()
    .addType(Roshambo.class)
    .registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(rock));

打印:
{
  '0x1': {'name': 'ROCK', 'beats': '0x2'},
  '0x2': {'name': 'SCISSORS', 'beats': '0x3'},
  '0x3': {'name': 'PAPER', 'beats': '0x1'}
}

请注意,GraphAdapterBuilder类是,而不是gson.jar中包含的。如果要使用它,则必须手动将其复制到项目中。

关于java - 删除双向递归关系的最简单方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10036958/

10-09 19:51