如何避免gson tojson递归

Ant*_*ton 2 java json gson

我的课很简单:

MyObject:
 - String index;
 - MyObject parent;
 - List<MyObject> childs;
Run Code Online (Sandbox Code Playgroud)

我想将存储的信息打印到json中。我使用Gson库的toJson函数。但是由于每个孩子都有到父对象的链接,因此我遇到了无限循环递归。有没有一种方法可以定义gson应该为每个孩子仅打印父索引而不是转储完整信息?

Mo1*_*989 5

您需要使用@Expose批注。

public class MyObject{

    @Expose
    String index;

    MyObject parent;

    @Expose
    List<MyObject> children;

}
Run Code Online (Sandbox Code Playgroud)

然后使用生成JSON

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
jsonString = gson.toJson(data);
Run Code Online (Sandbox Code Playgroud)

编辑:将其转换回对象时,可以进行dfs解析。只需执行以下方法:

public void setParents(MyObj patent){ 
    this.parent=parent; 
    for(MyObj o:children){
        o.setParent(this); 
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其称为根对象。