相关疑难解决方法(0)

Gson序列化多态对象列表

我正在尝试使用Gson将涉及多态的对象序列化/反序列化为JSON.

这是我的序列化代码:

ObixBaseObj lobbyObj = new ObixBaseObj();
lobbyObj.setIs("obix:Lobby");

ObixOp batchOp = new ObixOp();
batchOp.setName("batch");
batchOp.setIn("obix:BatchIn");
batchOp.setOut("obix:BatchOut");

lobbyObj.addChild(batchOp);

Gson gson = new Gson();
System.out.println(gson.toJson(lobbyObj));
Run Code Online (Sandbox Code Playgroud)

这是结果:

 {"obix":"obj","is":"obix:Lobby","children":[{"obix":"op","name":"batch"}]}
Run Code Online (Sandbox Code Playgroud)

序列化大多的作品,除了它缺少继承成员的内容(尤其是obix:BatchInobixBatchout字符串丢失).这是我的基类:

public class ObixBaseObj  {
    protected String obix;
    private String display;
    private String displayName;
    private ArrayList<ObixBaseObj> children;

    public ObixBaseObj()
    {
        obix = "obj";
    }

    public void setName(String name) {
        this.name = name;
    }
        ...
}
Run Code Online (Sandbox Code Playgroud)

这是我继承的类(ObixOp)的样子:

public class ObixOp extends ObixBaseObj {
    private String in;
    private String out;

    public ObixOp() { …
Run Code Online (Sandbox Code Playgroud)

java serialization json gson

42
推荐指数
3
解决办法
3万
查看次数

标签 统计

gson ×1

java ×1

json ×1

serialization ×1