I have never done much with serialization, but am trying to use Google's gson to serialize a Java object to a file. Here is an example of my issue:

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);
}
}

所以这很好地序列化了——但可以理解的是,删除了关于动物的类型信息:

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

This causes real problems for deserialization, though:

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.

I get why this is happening, but am having trouble figuring out the proper pattern for dealing with this. I did look in the guide but it didn't address this directly.

推荐答案

如果将动物设置为transient,则不会序列化.

Or you can serialize it yourself by implementing defaultWriteObject(...) and defaultReadObject(...) (I think thats what they were called...)

EDIT See the part about "Writing an Instance Creator" here.

GSON不能反序列化接口,因为它不知道将使用哪个实现类,所以您需要为Animal提供一个实例创建器,并设置一个默认值或类似的类.

Json相关问答推荐

替换字符串中特殊字符的Jolt变换

织女星-没有循环的动画条形图第二部分(实际上是织女星)

在Ansible中从json中提取特定数据

用 Jolt 替换 JSON 中的值

使用 jolt 变换展平嵌套 JSON - 非常复杂

jq 对特定键进行过滤并将值整理到单个 csv 单元格中

在Databricks中如何将JSON文件作为字典读取

如何在 Apps 脚本中循环遍历 JSON 响应

将请求中的数据推送到数组中

使用 jq 获取特定键的所有父键

Google GCM 服务器返回未经授权的错误 401

单元测试球衣 Restful Services

python,将Json写入文件

消息通知产生此内容无法显示

使用 jq 从 bash 中管道分隔的键和值创建 JSON

Jackson:忽略 Json 配置值

使用 Python 3 读取 JSON 文件

java.lang.BootstrapMethodError:调用站点#4 bootstrap 方法的异常,初始化 retrofit 时

运算符不存在:json = json

jq:按属性分组和键