Gson 多态对象列表序列化
Gson 提供了使用 RuntimeTypeAdapterFactory 序列化多态对象的解决方案。此类自动处理继承成员的序列化,无需编写自定义序列化程序。
实现
要使用 RuntimeTypeAdapterFactory,请按照以下步骤操作:
示例
<code class="java">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); RuntimeTypeAdapterFactory<ObixBaseObj> adapter = RuntimeTypeAdapterFactory .of(ObixBaseObj.class) .registerSubtype(ObixBaseObj.class) .registerSubtype(ObixOp.class); Gson gson2=new GsonBuilder().setPrettyPrinting().registerTypeAdapterFactory(adapter).create(); System.out.println(gson2.toJson(lobbyObj));</code>
输出
<code class="json">{ "type": "ObixBaseObj", "obix": "obj", "is": "obix:Lobby", "children": [ { "type": "ObixOp", "in": "obix:BatchIn", "out": "obix:BatchOut", "obix": "op", "name": "batch", "children": [] } ] }</code>
高级用例
要处理大量子类,请创建像 GsonUtils 这样的实用程序类来管理注册并提供集中的 Gson 实例。
<code class="java">public class GsonUtils { private static final GsonBuilder gsonBuilder = new GsonBuilder() .setPrettyPrinting(); public static void registerType( RuntimeTypeAdapterFactory<?> adapter) { gsonBuilder.registerTypeAdapterFactory(adapter); } public static Gson getGson() { return gsonBuilder.create(); } } public class ObixBaseObj { private static final RuntimeTypeAdapterFactory<ObixBaseObj> adapter = RuntimeTypeAdapterFactory.of(ObixBaseObj.class); private static final HashSet<Class<?>> registeredClasses= new HashSet<>(); static { GsonUtils.registerType(adapter); } private synchronized void registerClass() { if (!registeredClasses.contains(this.getClass())) { registeredClasses.add(this.getClass()); adapter.registerSubtype(this.getClass()); } } public ObixBaseObj() { registerClass(); obix = "obj"; } } public class ObixOp extends ObixBaseObj { private String in; private String out; public ObixOp() { super(); obix = "op"; } public ObixOp(String in, String out) { super(); obix = "op"; this.in = in; this.out = out; } }</code>
通过这种方法,多态对象的所有继承成员都将自动被序列化和反序列化,为处理复杂的继承层次结构提供了便捷的解决方案。
以上是如何使用 RuntimeTypeAdapterFactory 通过 Gson 序列化多态对象列表?的详细内容。更多信息请关注PHP中文网其他相关文章!