Class GraphAdapterBuilder

java.lang.Object
com.google.gson.graph.GraphAdapterBuilder

public final class GraphAdapterBuilder extends Object
A builder for constructing a graph-aware type adapter. This class allows you to register types for which cyclic references are allowed by serializing the graph of objects as a list of named nodes. This approach ensures that objects referencing each other (or themselves) are properly serialized and deserialized.

The builder maintains a mapping between types and their corresponding InstanceCreator instances. When a type is registered, it will be serialized using a graph adapter that assigns a unique identifier to each object instance. During deserialization, the graph adapter first builds a mapping from these identifiers to their JSON representations and then reconstructs the object graph.

Example usage:

   GraphAdapterBuilder graphBuilder = new GraphAdapterBuilder();
   graphBuilder.addType(MyClass.class);

   GsonBuilder gsonBuilder = new GsonBuilder();
   graphBuilder.registerOn(gsonBuilder);
   Gson gson = gsonBuilder.create();

   // Serialization
   String json = gson.toJson(myObject);

   // Deserialization
   MyClass deserialized = gson.fromJson(json, MyClass.class);
 
See Also:
  • Gson
  • GsonBuilder
  • Constructor Details

    • GraphAdapterBuilder

      public GraphAdapterBuilder()
  • Method Details

    • addType

      Registers the specified type with a default instance creator.
      Parameters:
      type - the type to register
      Returns:
      this builder instance for chaining
    • addType

      @CanIgnoreReturnValue public GraphAdapterBuilder addType(Type type, com.google.gson.InstanceCreator<?> instanceCreator)
      Registers the specified type with the provided instance creator.
      Parameters:
      type - the type to register
      instanceCreator - the instance creator used to create instances of the type during deserialization
      Returns:
      this builder instance for chaining
    • registerOn

      public void registerOn(com.google.gson.GsonBuilder gsonBuilder)
      Registers the graph adapter on the provided GsonBuilder. This method adds a TypeAdapterFactory and registers the necessary type adapters for all types previously registered via addType(Type).
      Parameters:
      gsonBuilder - the GsonBuilder on which to register the graph adapter