Home > Java > javaTutorial > How do you serialize polymorphic object lists with Gson using RuntimeTypeAdapterFactory?

How do you serialize polymorphic object lists with Gson using RuntimeTypeAdapterFactory?

Barbara Streisand
Release: 2024-10-30 15:13:02
Original
417 people have browsed it

How do you serialize polymorphic object lists with Gson using RuntimeTypeAdapterFactory?

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:

  1. Create an instance of RuntimeTypeAdapterFactory for the base class ObixBaseObj.
  2. Register all subclasses of ObixBaseObj using registerSubtype().
  3. Provide the RuntimeTypeAdapterFactory to the GsonBuilder using registerTypeAdapterFactory().

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template