繁体   English   中英

如何使用Gson解析扩展了基类的指定类?

[英]How to parse a specified class which extends a base class using Gson?

让我们首先说明属于其中的(基)类:

// the data class. This contains our values
public class Data<T extends Annotation> {
    public transient final T info; // gson ignores transients
    public Data(Class<T> annotation) { info = getClass().getAnnotation(annotation); }
}

// the manager class, this contains numerous Data's
public class Manager<T> {
    protected final ArrayList<T> collection = new ArrayList<T>();
    public Collection<T> GetCollection() { return collection; }
}

现在,假设我已按照以下方式实现了上述类:

// my implemented manager. It contains a bunch of MyBase objects
public class MyManager extends Manager<MyBase> {
    public MyManager() {
        collection.add(new MyCustomBase());
        // some more...
    }
}

public class MyBase extends MyData {
    // some stuff for my base, such as various methods for calculating and rendering
}

public MyData extends Data<MyData.MyInterface> {
    public String foo;
    MyData() {
        super(MyData.MyInterface.class);
        foo = info.foo(); // handle our interface variables, since interfaces cannot be directly modified
    }

    @Retention
    public @interface MyInterface {
        String foo();
    }

为了使代码易于理解,我的自定义库如下所示:

@MyData.MyInterface(foo = "bar")
public class CustomBase extends MyBase {
    // other various methods for rendering and calculating, some events in here too
}

现在,在GSON中,我想打印出MyData中的信息。 这是我尝试执行此操作的方式:

public class Config {
    // store the 'Managers' which we want to save the data of inside of an arrayList, and then iterate through them and their contents for 'Data', then just save it.
//...
Gson gson = new GsonBuilder().setPrettyPrinting().create();
PrintWriter writer = new PrintWriter(myJSON);
for (Manager m : managerList) {
    for (Object o : m.GetCollection()) {
        Data d = (Data) o;
        // expected result, a json with "foo": bar
        writer.println(gson.toJson(d)); // this doesn't work, throws a stack overflow
    }

    writer.close();
}

不幸的是,这种方法行不通。 由于某些奇怪的原因,它引发了堆栈溢出。 有什么更好的方法呢?

编辑:由于foo,我将不会直接处理接口,否则在程序执行过程中任何其他值都会更改。

我设法通过使用@Expose注释来避免此问题:

public MyData {
    @Expose public String foo;
}

然后,在使用GsonBuilder创建Gson时,只需使用excludeFieldWithoutExposeAnnotation()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM