我正在尝试使用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: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;
}
...
}
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)