Gson Java Library

repository·main·Indexed 12 days ago

https://github.com/google/gson

A Java library for converting Java objects to JSON and JSON strings back into Java objects. It supports arbitrary objects without requiring source code access, provides extensive support for Java Generics, and includes a specialized protobuf module for Protocol Buffers serialization. Compatible with Java 6+ and Android API level 19+, with recommended version 2.14.0.

Tokens
11.4K
Snippets
36
Records
56
Agent score
98%

What's inside Gson

  1. Overview of Gson

    main

    Gson is a Java library designed to convert Java Objects into their JSON representation (serialization) and convert JSON strings back into equivalent Java objects (deserialization).

    Key capabilities include:

    • Working with arbitrary Java objects, including those without available source code.
    • Supporting complex, nested object structures.
    • Providing mechanisms for custom object representations.
    • Generating both compact and human-readable (pretty-printed) JSON output.
  2. Use the Gson Protobuf module for JSON serialization

    main

    The proto module provides a specialized JSON serializer and deserializer for Protocol Buffers (protobuf) messages. This allows you to convert protobuf-generated Java objects to and from JSON format using Gson.

    Note: The artifacts created by this module are currently not deployed to Maven Central. You may need to build the module locally or include it via a local repository dependency.

  3. Serialize and deserialize Maps

    main

    By default, Gson serializes java.util.Map as a JSON object.

    Key behaviors:

    • Key Conversion: Since JSON keys must be strings, Gson calls toString() on Map keys. null keys are converted to the string "null".
    • Deserialization: Requires a TypeToken to specify the types of keys and values.
    • Complex Map Keys: To use complex objects as keys without relying on toString(), use GsonBuilder.enableComplexMapKeySerialization(). This will serialize the Map as a JSON array of key-value pairs if any key is a complex type (array or object).
    // Standard Map Serialization
    Gson gson = new Gson();
    Map<String, String> stringMap = new LinkedHashMap<>();
    stringMap.put("key", "value");
    stringMap.put(null, "null-entry");
    String json = gson.toJson(stringMap); // ==> {"key":"value","null":"null-entry"}
    
    // Complex Map Key Serialization
    Gson gsonComplex = new GsonBuilder().enableComplexMapKeySerialization().create();
    Map<PersonName, Integer> complexMap = new LinkedHashMap<>();
    // ... put items ...
    String jsonComplex = gsonComplex.toJson(complexMap);
    // ==> [[{"firstName":"John","lastName":"Doe"},30], ...]
  4. Configure reflection metadata for GraalVM Native Image

    main

    GraalVM Native Image requires explicit configuration of class members accessed via reflection.

    When using Gson with Native Image, you can use the existing reflection metadata provided in the repository located at: src/test/resources/META-INF/native-image/reflect-config.json.

    Alternatively, you can automatically generate a metadata file by running tests with the -Dagent=true flag, which utilizes the GraalVM Maven plugin's agent support.

    # Example of running with the agent to generate metadata
    mvn clean test --activate-profiles native-image-test -Dagent=true
  5. Serialize and deserialize objects

    main

    Gson converts Java objects to JSON and vice versa.

    Key behaviors:

    • Private Fields: It is recommended to use private fields; Gson handles them automatically.
    • No Annotations Needed: All fields in the current class and superclasses are included by default.
    • Transient Fields: Fields marked transient are ignored.
    • Null Handling: During serialization, null fields are omitted. During deserialization, missing JSON entries result in the field being set to its default value (null for objects, zero for numbers, false for booleans).
    • Synthetic Fields: Ignored by default.
    • Inner Classes: Pure inner classes (non-static) cannot be automatically deserialized because they require a reference to the containing object. To fix this, make the inner class static or provide a custom InstanceCreator.
    • Anonymous/Local Classes: These are excluded and serialized as null.
    class BagOfPrimitives {
      private int value1 = 1;
      private String value2 = "abc";
      private transient int value3 = 3;
      BagOfPrimitives() {}
    }
    
    // Serialization
    BagOfPrimitives obj = new BagOfPrimitives();
    Gson gson = new Gson();
    String json = gson.toJson(obj);
    // ==> {"value1":1,"value2":"abc"}
    
    // Deserialization
    BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
  6. How Gson handles deserialization and schema validation

    main

    When deserializing a JSON string into a Java object, Gson navigates the type tree of the target object rather than the JSON tree.

    This approach provides several benefits:

    • Schema Validation: It validates the input against your expected Java types.
    • Strict Control: It ensures only the expected types are instantiated.
    • Field Filtering: It automatically ignores any extra fields present in the JSON input that do not correspond to fields in your target Java class.
  7. Extending Gson functionality with Custom Serializers and Deserializers

    main
    If you need to serialize or deserialize classes that you do not control (such as JDK classes or third-party library classes) and cannot add annotations to them, you should define custom serializers and deserializers. This allows you to define custom mapping logic externally without modifying the target class's source code.
  8. Instantiate Gson using Gson and GsonBuilder

    main

    The primary entry point for the library is the Gson class.

    • new Gson(): Creates a default instance of Gson with standard settings.
    • GsonBuilder: Use this class when you need to customize the Gson instance, such as configuring versioning support, field naming strategies, or custom serialization behaviors.

    Gson instances are stateless and thread-safe; you can and should reuse a single Gson instance for multiple serialization and deserialization operations to improve performance.

    // Create a default instance
    Gson gson = new Gson();
    
    // Create a customized instance
    Gson customGson = new GsonBuilder()
        .setPrettyPrinting()
        .create();
  9. Use Versioning with @Since annotation

    main

    You can manage different versions of an object by using the @Since(version) annotation on classes or fields. To enforce this, configure your Gson instance with setVersion(version). Fields with a version higher than the configured version will be ignored.

    public class VersionedClass {
      @Since(1.1) private final String newerField;
      @Since(1.0) private final String newField;
      private final String field;
      // ...
    }
    
    // Only serializes fields with version <= 1.0
    Gson gson = new GsonBuilder().setVersion(1.0).create();
    String jsonOutput = gson.toJson(versionedObject);
  10. How Gson maps JSON elements to Java fields

    main

    Gson is fields-based. It uses all fields in the inheritance hierarchy to deduce JSON elements, with the following exceptions:

    • Excluded fields: Fields marked as transient, static, or synthetic are ignored.
    • Getters/Setters: Unlike some libraries that use getters (e.g., getXXX or isXXX), Gson relies on the fields themselves. This avoids issues where getter names are semantic rather than property-based.
  11. Configure JPMS dependencies for Java 9+

    main

    If you are running on Java 9 or newer, Gson provides a JPMS module descriptor (module name com.google.gson). You may optionally include the following JDK modules:

    • java.sql: Enables default adapters for certain SQL date and time classes.
    • jdk.unsupported: Allows Gson to use sun.misc.Unsafe to create instances of classes that lack a no-args constructor. Warning: Use this with caution as Unsafe is not available in all environments. You can disable this behavior using GsonBuilder.disableJdkUnsafe().
  12. Understand Gson's core capabilities

    main

    Gson is a Java library designed to convert Java Objects into JSON representations and vice-versa.

    Key Features:

    • Simple API: Provides toJson() and fromJson() methods for easy conversion.
    • No Annotations Required: Unlike many other libraries, Gson can work with arbitrary Java objects, including pre-existing classes where you cannot modify the source code to add annotations.
    • Generics Support: Extensive support for Java Generics.
    • Complex Object Support: Handles deep inheritance hierarchies and complex generic types.
    • Customization: Allows for custom representations of objects.