Class GraphAdapterBuilder


  • public final class GraphAdapterBuilder
    extends java.lang.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
    • Field Detail

      • instanceCreators

        private final java.util.Map<java.lang.reflect.Type,​InstanceCreator<?>> instanceCreators
    • Constructor Detail

      • GraphAdapterBuilder

        public GraphAdapterBuilder()
    • Method Detail

      • addType

        public GraphAdapterBuilder addType​(java.lang.reflect.Type type)
        Registers the specified type with a default instance creator.
        Parameters:
        type - the type to register
        Returns:
        this builder instance for chaining
      • addType

        public GraphAdapterBuilder addType​(java.lang.reflect.Type type,
                                           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​(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