Home  >  Article  >  Java  >  How to Serialize a List of Polymorphic Objects with Gson Using RuntimeTypeAdapterFactory?

How to Serialize a List of Polymorphic Objects with Gson Using RuntimeTypeAdapterFactory?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 05:05:02271browse

How to Serialize a List of Polymorphic Objects with Gson Using RuntimeTypeAdapterFactory?

How to Serialize a List of Polymorphic Objects with Gson

When dealing with polymorphic objects during serialization, inheritance and class hierarchy can pose challenges. One method to address this elegantly is through Gson's RuntimeTypeAdapterFactory.

Let's consider an example where we have a base class, ObixBaseObj, and a child class, ObixOp. Our goal is to serialize an instance of ObixBaseObj that contains a collection of children, including ObixOp.

In the first code snippet, we encounter an issue where inherited members (specifically, in and out strings) are missing during serialization. The solution lies in using RuntimeTypeAdapterFactory:

<code class="java">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>

Working Example

For a scenario where multiple subclasses inherit from ObixBaseObj, we can implement a custom registration mechanism within ObixBaseObj and utilize a utility class, GsonUtils:

<code class="java">public class ObixBaseObj {
    // ...
    private static final RuntimeTypeAdapterFactory<ObixBaseObj> adapter = 
            RuntimeTypeAdapterFactory.of(ObixBaseObj.class);

    public static void registerType(
            RuntimeTypeAdapterFactory<?> adapter) {
        GsonUtils.registerType(adapter);
    }

    // ...
}

public class ObixOp extends ObixBaseObj {
    // ...
    public ObixOp() {
        super();
        obix = "op";
    }

    // ...
}</code>

In GsonUtils:

<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();
    }
}</code>
<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);

Gson gson = GsonUtils.getGson();
System.out.println(gson.toJson(lobbyObj));</code>

This approach simplifies the serialization of polymorphic objects by automatically registering subclasses and ensuring that inherited members are included in the serialized output.

The above is the detailed content of How to Serialize a List of Polymorphic Objects with Gson Using RuntimeTypeAdapterFactory?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn