猿问

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

这是结果:


 {"obix":"obj","is":"obix:Lobby","children":[{"obix":"op","name":"batch"}]}

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


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;

    }

        ...

}

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


public class ObixOp extends ObixBaseObj {

    private String in;

    private String out;


    public ObixOp() {

        obix = "op";

    }

    public ObixOp(String in, String out) {

        obix = "op";

        this.in = in;

        this.out = out;

    }

    public String getIn() {

        return in;

    }

    public void setIn(String in) {

        this.in = in;

    }

    public String getOut() {

        return out;

    }

    public void setOut(String out) {

        this.out = out;

    }

}

我知道我可以使用适配器,但问题是我正在序列化基类类型的集合ObixBaseObj。大约有25个类继承自此。我怎样才能优雅地完成这项工作?


饮歌长啸
浏览 799回答 3
3回答
随时随地看视频慕课网APP

相关分类

Java
我要回答