gson,parent< - >儿童循环参考

时间:2017-11-02 17:23:01

标签: java android gson

我的对象序列化存在问题。下面是一个简化的例子:

public class Parent {
  private String name;
  private String id;
  private List<Child> children;

  public Parent (String name) {
    this.name = name;
    this.children = children;
    id = UUID.randomUUID().toString();

  // getters and setters

  }
}

public class Child {
  private name;
  private parent;
  private id;

  public Child(String name, Parent parent) {
    this.name = name;
    this.parent = parent;
    id = UUID.randomUUID().toString();
  }
}

然后我说我运行以下代码:

Parent mother = new Parent(BigMoma);
Child baby = new Child(Cutie);
mother.getChildren.add(baby); //you get the concept

这使得对象具有相互引用,因此无法使用标准Gson调用进行序列化。

我还尝试使用看起来像这样的Gson适配器:

public class ChildSerializer implements JsonSerializer<Child> {
@Override
public JsonElement serialize(Child src, Type typeOfSrc, 
JsonSerializationContext context) {
    JsonObject result = new JsonObject();
    result.add("name", new JsonPrimitive(src.getName()));
    result.add("id", new JsonPrimitive(src.getId()));
    result.add("parentId", new JsonPrimitive(src.getParent().getId()));

    return result;
}

运行时没有达到预期的效果:

Gson gson = new GsonBuilder().registerTypeAdapter(Child.class, new 
ChildSerializer()).create();
        String serializedDatabaseObject = gson.toJson(baby);

我做错了什么?我该怎么办?

0 个答案:

没有答案