Gson Serialization of Polymorphic Object Lists
Gson provides a solution to serialize polymorphic objects using RuntimeTypeAdapterFactory. This class automatically handles the serialization of inherited members, eliminating the need for writing custom serializers.
Implementation
To use RuntimeTypeAdapterFactory, follow these steps:
Example
<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>
Output
<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>
Advanced Use Case
To handle a large number of subclasses, create a utility class like GsonUtils to manage registration and provide a centralized Gson instance.
<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>
With this approach, all inherited members of polymorphic objects will be automatically serialized and deserialized, providing a convenient solution for handling complex inheritance hierarchies.
The above is the detailed content of How do you serialize polymorphic object lists with Gson using RuntimeTypeAdapterFactory?. For more information, please follow other related articles on the PHP Chinese website!