删除双向递归关系的最简单方法是什么?

时间:2012-04-05 22:35:07

标签: java recursion gson

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

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来终止递归关系。

在您看来,这是一个很好的解决方案,还是有其他方法更实用? 感谢

5 个答案:

答案 0 :(得分:26)

有一个名为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'}
}

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

答案 1 :(得分:2)

我不知道Gson,但我和杰克逊合作。查找使用其ObjectMapper类的示例。至于递归,使用@JsonManagedReference和@JsonBackReference来阻止它。看看那些例如用法。

答案 2 :(得分:1)

您可以使用@Expose(serialize = false)来避免序列化Collection。

答案 3 :(得分:1)

我将GsonBuilder配置为与杰克逊注释一起使用:

GsonBuilder builder = new GsonBuilder()
    .addSerializationExclusionStrategy(serializationExclusionStrategy);

final ExclusionStrategy serializationExclusionStrategy = new ExclusionStrategy() {
  @Override
  public boolean shouldSkipField(FieldAttributes f) {
    return f.getAnnotation(JsonIgnore.class) != null
           || f.getAnnotation(JsonBackReference.class) != null;
  }

  @Override
  public boolean shouldSkipClass(Class<?> aClass) {
    return false;
  }
};

答案 4 :(得分:0)

使用瞬态忽略google.gson的@OneToMany集

相关问题