一尘不染

如何使用接口序列化一个类?

json

我从未对序列化做过很多事情,但是正在尝试使用Google的gson将Java对象序列化为文件。这是我的问题的一个示例:

public interface Animal {
    public String getName();
}


 public class Cat implements Animal {

    private String mName = "Cat";
    private String mHabbit = "Playing with yarn";

    public String getName() {
        return mName;
    }

    public void setName(String pName) {
        mName = pName;
    }

    public String getHabbit() {
        return mHabbit;
    }

    public void setHabbit(String pHabbit) {
        mHabbit = pHabbit;
    }

}

public class Exhibit {

    private String mDescription;
    private Animal mAnimal;

    public Exhibit() {
        mDescription = "This is a public exhibit.";
    }

    public String getDescription() {
        return mDescription;
    }

    public void setDescription(String pDescription) {
        mDescription = pDescription;
    }

    public Animal getAnimal() {
        return mAnimal;
    }

    public void setAnimal(Animal pAnimal) {
        mAnimal = pAnimal;
    }

}

public class GsonTest {

public static void main(String[] argv) {
    Exhibit exhibit = new Exhibit();
    exhibit.setAnimal(new Cat());
    Gson gson = new Gson();
    String jsonString = gson.toJson(exhibit);
    System.out.println(jsonString);
    Exhibit deserializedExhibit = gson.fromJson(jsonString, Exhibit.class);
    System.out.println(deserializedExhibit);
}
}

因此,这很好地进行了序列化-但可以理解的是,它删除了Animal上的类型信息:

{"mDescription":"This is a public exhibit.","mAnimal":{"mName":"Cat","mHabbit":"Playing with yarn"}}

但是,这会导致反序列化的实际问题:

Exception in thread "main" java.lang.RuntimeException: No-args constructor for interface com.atg.lp.gson.Animal does not exist. Register an InstanceCreator with Gson for this type to fix this problem.

我知道为什么会发生这种情况,但是在弄清楚处理这种情况的正确模式时遇到了麻烦。我确实看过指南,但并未直接解决。


阅读 233

收藏
2020-07-27

共1个答案

一尘不染

将动物标为transient,则不会序列化。

或者,您可以自己通过实现defaultWriteObject(...)和进行序列化defaultReadObject(...)(我认为这就是所谓的…)

编辑此处参阅有关“编写实例创建器”的部分。

Gson无法反序列化接口,因为它不知道将使用哪个实现类,因此您需要为Animal提供实例创建者并设置默认值或类似值。

2020-07-27