Package com.google.gson.graph
Class GraphAdapterBuilder
java.lang.Object
com.google.gson.graph.GraphAdapterBuilder
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:
-
GsonGsonBuilder
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionRegisters the specified type with a default instance creator.Registers the specified type with the provided instance creator.voidregisterOn(com.google.gson.GsonBuilder gsonBuilder) Registers the graph adapter on the providedGsonBuilder.
-
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 registerinstanceCreator- 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 providedGsonBuilder. This method adds aTypeAdapterFactoryand registers the necessary type adapters for all types previously registered viaaddType(Type).- Parameters:
gsonBuilder- theGsonBuilderon which to register the graph adapter
-