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中文網其他相關文章!