### Gson User Guide Source: https://github.com/google/gson/blob/main/README.md A link to the user guide which contains examples and instructions on how to use Gson in Java projects for JSON serialization and deserialization. ```markdown [User guide](UserGuide.md) ``` -------------------------------- ### Maven Settings Configuration Example Source: https://github.com/google/gson/blob/main/ReleaseProcess.md An example structure for the Maven settings.xml file, typically used to configure repository access and credentials for deployment. ```xml sonatype-nexus-snapshots your-username your-encrypted-password gpg true your-gpg-passphrase ``` -------------------------------- ### Instance Creator for Money Class Source: https://github.com/google/gson/blob/main/UserGuide.md Shows an example of an InstanceCreator for a custom Money class. This is useful when a class does not have a no-argument constructor and Gson needs to create an instance during deserialization. ```java private class MoneyInstanceCreator implements InstanceCreator { public Money createInstance(Type type) { return new Money("1000000", CurrencyCode.USD); } } ``` -------------------------------- ### Using GsonBuilder Source: https://github.com/google/gson/blob/main/UserGuide.md Illustrates how to use GsonBuilder to create a Gson instance with custom configurations, such as pretty printing or versioning. ```java import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonBuilderExample { public static void main(String[] args) { MyObject obj = new MyObject("Pretty JSON", 789); // Create Gson instance with pretty printing enabled Gson gson = new GsonBuilder().setPrettyPrinting().create(); String prettyJson = gson.toJson(obj); System.out.println(prettyJson); } } class MyObject { private String name; private int number; public MyObject(String name, int number) { this.name = name; this.number = number; } public String getName() { return name; } public int getNumber() { return number; } } ``` -------------------------------- ### Gson Troubleshooting Guide Source: https://github.com/google/gson/blob/main/README.md A link to the troubleshooting guide that addresses common issues encountered when using Gson, including specific sections on ProGuard/R8. ```markdown [Troubleshooting guide](Troubleshooting.md) ``` ```markdown [Troubleshooting guide](Troubleshooting.md#proguard-r8) ``` -------------------------------- ### Example of Serializing Null Values Source: https://github.com/google/gson/blob/main/UserGuide.md Provides a practical example demonstrating the effect of serializeNulls(). It shows the JSON output for an object with a null field and for a null object itself. ```java public class Foo { private final String s; private final int i; public Foo() { this(null, 5); } public Foo(String s, int i) { this.s = s; this.i = i; } } Gson gson = new GsonBuilder().serializeNulls().create(); Foo foo = new Foo(); String json = gson.toJson(foo); System.out.println(json); json = gson.toJson(null); System.out.println(json); ``` -------------------------------- ### Add Gson Dependency with Gradle Source: https://github.com/google/gson/blob/main/UserGuide.md This snippet shows how to include the Gson library in your Gradle project. Ensure you have a compatible Java version and Gradle setup. ```gradle dependencies { implementation 'com.google.code.gson:gson:2.13.1' } ``` -------------------------------- ### InstanceCreator for Parameterized MyList Source: https://github.com/google/gson/blob/main/UserGuide.md Demonstrates how to implement InstanceCreator for a parameterized type like MyList. It shows that for simple cases, the raw type can be used, simplifying instantiation. ```java class MyList extends ArrayList { } class MyListInstanceCreator implements InstanceCreator> { @SuppressWarnings("unchecked") public MyList createInstance(Type type) { // No need to use a parameterized list since the actual instance will have the raw type anyway. return new MyList(); } } ``` -------------------------------- ### Configuring Maven for Sonatype Deployment Source: https://github.com/google/gson/blob/main/ReleaseProcess.md Configuration steps for a machine to deploy artifacts to the Sonatype Repository, including GPG setup, encrypted passwords, and Maven settings.xml. ```plaintext Install/Configure GPG following this guide. Create encrypted passwords. Create ~/.m2/settings.xml similar to as described in Doclava release process. Now for deploying a snapshot repository, use mvn deploy. ``` -------------------------------- ### Local Maven Release Workflow Setup Source: https://github.com/google/gson/blob/main/ReleaseProcess.md Steps to set up a local environment for testing the Maven release workflow. This involves initializing a bare Git repository, configuring the pom.xml with local repository paths, and setting up remotes. ```sh git init --bare --initial-branch=main . ``` ```txt scm:git:file:///#gson-remote-temp#/git-repo file:///#gson-remote-temp#/maven-repo ``` ```txt git remote set-url origin file:///#gson-remote-temp#/git-repo ``` ```sh git push origin main ``` ```sh mvn release:clean ``` ```sh mvn release:prepare ``` ```sh mvn release:perform ``` -------------------------------- ### Gson Versioning with @Since Annotation Source: https://github.com/google/gson/blob/main/UserGuide.md Demonstrates how to use the @Since annotation to manage different versions of an object. Fields annotated with @Since are included or excluded based on the Gson instance's version setting. The example shows how setting a version on the Gson builder affects the serialized output. ```java public class VersionedClass { @Since(1.1) private final String newerField; @Since(1.0) private final String newField; private final String field; public VersionedClass() { this.newerField = "newer"; this.newField = "new"; this.field = "old"; } } VersionedClass versionedObject = new VersionedClass(); Gson gson = new GsonBuilder().setVersion(1.0).create(); String jsonOutput = gson.toJson(versionedObject); System.out.println(jsonOutput); System.out.println(); gson = new Gson(); jsonOutput = gson.toJson(versionedObject); System.out.println(jsonOutput); ``` ```json {"newField":"new","field":"old"} {"newerField":"newer","newField":"new","field":"old"} ``` -------------------------------- ### Output of Serializing Null Values Example Source: https://github.com/google/gson/blob/main/UserGuide.md The resulting JSON output when serializing an object with null fields and a null object using Gson's serializeNulls() configuration. ```json {"s":null,"i":5} null ``` -------------------------------- ### Gson Usage Example Source: https://github.com/google/gson/blob/main/README.md This is a conceptual example of how Gson is used for JSON conversion. It demonstrates the basic `toJson()` and `fromJson()` methods for converting Java objects to JSON strings and vice-versa. Actual implementation would involve creating Gson instances and handling data structures. ```java // Example of converting a Java object to JSON // Gson gson = new Gson(); // String json = gson.toJson(myObject); // Example of converting a JSON string to a Java object // MyObject obj = gson.fromJson(jsonString, MyObject.class); ``` -------------------------------- ### Gson ProGuard Configuration Source: https://github.com/google/gson/blob/main/Troubleshooting.md Provides guidance for older Gson versions or non-Android ProGuard configurations. It suggests copying rules from Gson's `gson.pro` file into the project's ProGuard configuration to ensure proper minification. ```java // Copy rules from gson/src/main/resources/META-INF/proguard/gson.pro // into your project's ProGuard configuration file. ``` -------------------------------- ### Set ANDROID_HOME Environment Variable Source: https://github.com/google/gson/blob/main/ReleaseProcess.md Set the ANDROID_HOME environment variable to the path of the Android SDK installation directory. This is a common prerequisite for Android development tools like Vogar. ```bash export ANDROID_HOME=~/apps/android-sdk-mac_x86 ``` -------------------------------- ### Basic Gson Usage Source: https://github.com/google/gson/blob/main/UserGuide.md Demonstrates the fundamental usage of Gson for converting Java objects to JSON and vice-versa. This involves creating a Gson instance and using its toJson() and fromJson() methods. ```java import com.google.gson.Gson; public class GsonExample { public static void main(String[] args) { // Java object to JSON MyObject obj = new MyObject("Hello", 123); Gson gson = new Gson(); String json = gson.toJson(obj); System.out.println(json); // JSON to Java object String jsonString = "{\"name\":\"World\",\"number\":456}"; MyObject obj2 = gson.fromJson(jsonString, MyObject.class); System.out.println(obj2.getName() + ", " + obj2.getNumber()); } } class MyObject { private String name; private int number; public MyObject(String name, int number) { this.name = name; this.number = number; } public String getName() { return name; } public int getNumber() { return number; } } ``` -------------------------------- ### Gson Custom Exclusion Strategy Source: https://github.com/google/gson/blob/main/UserGuide.md Illustrates how to implement a custom `ExclusionStrategy` to exclude fields based on annotations or types. The example excludes fields annotated with `@Foo` and top-level types of class `String`. This allows for fine-grained control over which fields are included or excluded during serialization and deserialization. ```java @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface Foo { // Field tag only annotation } public class SampleObjectForTest { @Foo private final int annotatedField; private final String stringField; private final long longField; public SampleObjectForTest() { annotatedField = 5; stringField = "someDefaultValue"; longField = 1234; } } public class MyExclusionStrategy implements ExclusionStrategy { private final Class typeToSkip; private MyExclusionStrategy(Class typeToSkip) { this.typeToSkip = typeToSkip; } public boolean shouldSkipClass(Class clazz) { return (clazz == typeToSkip); } public boolean shouldSkipField(FieldAttributes f) { return f.getAnnotation(Foo.class) != null; } } public static void main(String[] args) { Gson gson = new GsonBuilder() .setExclusionStrategies(new MyExclusionStrategy(String.class)) .serializeNulls() .create(); SampleObjectForTest src = new SampleObjectForTest(); String json = gson.toJson(src); System.out.println(json); } ``` ```json {"longField":1234} ``` -------------------------------- ### Debugging Gson Version Conflicts Source: https://github.com/google/gson/blob/main/Troubleshooting.md Provides code to help identify Gson version conflicts on the classpath by printing the location of the Gson class. ```java System.out.println(Gson.class.getProtectionDomain().getCodeSource().getLocation()); ``` -------------------------------- ### Custom JsonSerializer for DateTime Source: https://github.com/google/gson/blob/main/UserGuide.md Provides an example of a custom JsonSerializer for the JodaTime DateTime class. The serialize method converts a DateTime object to its string representation for JSON output. ```java private class DateTimeSerializer implements JsonSerializer { public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.toString()); } } ``` -------------------------------- ### Gson InstanceCreator and TypeAdapter Documentation Source: https://github.com/google/gson/blob/main/Troubleshooting.md Gson provides mechanisms for custom object creation and serialization/deserialization. InstanceCreator is used when a class cannot be instantiated directly, and TypeAdapter offers more control over the JSON mapping process. ```APIDOC Gson API Documentation: InstanceCreator: Used to create instances of classes that cannot be instantiated directly (e.g., abstract classes, interfaces, or classes without public no-arg constructors). - Signature: InstanceCreator - Method: createInstance(Type type) - Creates an instance of the specified type. - Parameters: - type: The type of object to create. - Returns: An instance of the specified type. TypeAdapter: Provides fine-grained control over the serialization and deserialization of a specific Java type to and from JSON. - Signature: TypeAdapter - Methods: - write(JsonWriter out, T value) throws IOException - Serializes the Java object 'value' to the JSON output stream 'out'. - read(JsonReader in) throws IOException - Deserializes a JSON value from the input stream 'in' to a Java object. - Usage: Implement this interface and register it with GsonBuilder using registerTypeAdapter(). ``` -------------------------------- ### Maven Dependency for Gson Source: https://github.com/google/gson/blob/main/UserGuide.md This snippet shows how to add the Gson library as a compile-time dependency to a Maven project, enabling Java to JSON conversion. ```xml com.google.code.gson gson 2.13.1 compile ``` -------------------------------- ### Gson Field Naming Policy and @SerializedName Annotation Source: https://github.com/google/gson/blob/main/UserGuide.md Demonstrates how to use Gson's FieldNamingPolicy to convert Java field names to JSON field names and how to use the @SerializedName annotation for custom naming on a per-field basis. This example shows the conversion of a Java object to a JSON string with a custom field name. ```java private class SomeObject { @SerializedName("custom_naming") private final String someField; private final String someOtherField; public SomeObject(String a, String b) { this.someField = a; this.someOtherField = b; } } SomeObject someObject = new SomeObject("first", "second"); Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); String jsonRepresentation = gson.toJson(someObject); System.out.println(jsonRepresentation); ``` ```json {"custom_naming":"first","SomeOtherField":"second"} ``` -------------------------------- ### InstanceCreator for Parameterized Id Type Source: https://github.com/google/gson/blob/main/UserGuide.md Illustrates creating an instance for a parameterized type like Id, where the type parameter is crucial. It uses the passed 'type' argument to determine the actual type argument for instantiation. ```java public class Id { private final Class classOfId; private final long value; public Id(Class classOfId, long value) { this.classOfId = classOfId; this.value = value; } } class IdInstanceCreator implements InstanceCreator> { public Id createInstance(Type type) { Type[] typeParameters = ((ParameterizedType)type).getActualTypeArguments(); Type idType = typeParameters[0]; // Id has only one parameterized type T return new Id((Class)idType, 0L); } } ``` -------------------------------- ### R8 Configuration to Keep Constructors Source: https://github.com/google/gson/blob/main/Troubleshooting.md This R8 configuration snippet ensures that the no-args constructor of a specific class is preserved during code shrinking. This is crucial for libraries like Gson that rely on these constructors for deserialization. ```proguard # Keep the no-args constructor of the deserialized class -keepclassmembers class com.example.MyClass { (); } ``` -------------------------------- ### Gson @Expose Annotation Source: https://github.com/google/gson/blob/main/UserGuide.md Demonstrates how to use the `@Expose` annotation to control which fields are serialized and deserialized. When `excludeFieldsWithoutExposeAnnotation()` is used, only fields annotated with `@Expose` will be included. ```java new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create() ``` -------------------------------- ### Pretty Printing JSON Output Source: https://github.com/google/gson/blob/main/UserGuide.md Configures Gson to produce pretty-printed JSON output with whitespace and indentation. This is achieved by using the GsonBuilder and setting the pretty printing option. ```java Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonOutput = gson.toJson(someObject); ``` -------------------------------- ### Registering Custom Type Adapters in Gson Source: https://github.com/google/gson/blob/main/UserGuide.md Demonstrates how to register custom serializers, deserializers, and instance creators for specific types using GsonBuilder. It highlights the checks performed by registerTypeAdapter to prevent overriding built-in adapters. ```java GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter(MyType2.class, new MyTypeAdapter()); gson.registerTypeAdapter(MyType.class, new MySerializer()); gson.registerTypeAdapter(MyType.class, new MyDeserializer()); gson.registerTypeAdapter(MyType.class, new MyInstanceCreator()); ``` -------------------------------- ### Gson Map Deserialization with TypeToken Source: https://github.com/google/gson/blob/main/UserGuide.md Illustrates deserializing JSON into a `java.util.Map` using Gson. A `TypeToken` is required to specify the key and value types of the Map for correct deserialization. ```java Gson gson = new Gson(); TypeToken> mapType = new TypeToken>(){}; String json = "{\"key\": \"value\"}"; // Deserialization // Note: For older Gson versions it is necessary to use `mapType.getType()` as argument below, // this is however not type-safe and care must be taken to specify the correct type for the local variable Map stringMap = gson.fromJson(json, mapType); // ==> stringMap is {key=value} ``` -------------------------------- ### Configure Java Module for Gson Reflection Source: https://github.com/google/gson/blob/main/Troubleshooting.md This snippet shows how to configure your `module-info.java` file to allow Gson to use reflection on your classes. This is necessary when encountering 'module ... does not "opens ..." to module com.google.gson' exceptions. ```java module mymodule { requires com.google.gson; opens mypackage to com.google.gson; } ``` -------------------------------- ### Preventing Reflection on Platform Classes with Gson Source: https://github.com/google/gson/blob/main/Troubleshooting.md Demonstrates how to use Gson's ReflectionAccessFilter to prevent accidental reflection on internal Android fields, which can cause unexpected JSON output changes. ```java Gson gson = new GsonBuilder() .addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_ALL_PLATFORM) .create(); ``` -------------------------------- ### Gson Collection Serialization and Deserialization Source: https://github.com/google/gson/blob/main/UserGuide.md Demonstrates serializing a Java Collection to JSON and deserializing it back into a Collection of a specific generic type using Gson. It highlights the requirement to define the generic type for deserialization. ```java Gson gson = new Gson(); Collection ints = Arrays.asList(1,2,3,4,5); // Serialization String json = gson.toJson(ints); // ==> [1,2,3,4,5] // Deserialization TypeToken> collectionType = new TypeToken>(){}; // Note: For older Gson versions it is necessary to use `collectionType.getType()` as argument below, // this is however not type-safe and care must be taken to specify the correct type for the local variable Collection ints2 = gson.fromJson(json, collectionType); // ==> ints2 is same as ints ``` -------------------------------- ### Reflection Metadata Configuration for GraalVM Native Image Source: https://github.com/google/gson/blob/main/test-graal-native-image/README.md Example JSON structure for specifying reflection metadata required by GraalVM Native Image. This configuration informs the native image builder about classes and members that need to be accessible via reflection. ```json [ { "name": "com.google.gson.SomeClass", "methods": [ { "name": "someMethod", "parameterTypes": ["java.lang.String"] } ], "fields": [ { "name": "someField" } ] } ] ``` -------------------------------- ### Handling ClassCastException with TypeToken Source: https://github.com/google/gson/blob/main/Troubleshooting.md Addresses ClassCastException by recommending the use of TypeToken for type-safe deserialization, especially with collections. It advises against raw types and highlights the importance of using Gson's fromJson overloads with TypeToken. ```java import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; // Avoid raw types: Instead of calling fromJson(..., List.class), create for example a TypeToken>. TypeToken> listType = new TypeToken>() {}; List myObjects = gson.fromJson(jsonString, listType.getType()); // When using TypeToken prefer the Gson.fromJson overloads with TypeToken parameter // such as fromJson(Reader, TypeToken). // List myObjects = gson.fromJson(reader, listType); // Avoid capturing a type variable like new TypeToken>() {}. // Instead use TypeToken.getParameterized(List.class, elementType) // Example: TypeToken.getParameterized(List.class, String.class); ``` -------------------------------- ### Gson Primitives Serialization and Deserialization Source: https://github.com/google/gson/blob/main/UserGuide.md Demonstrates how to use Gson to serialize primitive Java types (integers, strings, booleans) into JSON format and deserialize JSON strings back into their corresponding Java types. ```java // Serialization Gson gson = new Gson(); gson.toJson(1); // ==> 1 gson.toJson("abcd"); // ==> "abcd" gson.toJson(new Long(10)); // ==> 10 int[] values = { 1 }; gson.toJson(values); // ==> [1] // Deserialization int i = gson.fromJson("1", int.class); Integer intObj = gson.fromJson("1", Integer.class); Long longObj = gson.fromJson("1", Long.class); Boolean boolObj = gson.fromJson("false", Boolean.class); String str = gson.fromJson("\"abc\"", String.class); String[] strArray = gson.fromJson("[\"abc\"]", String[].class); ``` -------------------------------- ### Gson: Malformed JSON Exception Location Source: https://github.com/google/gson/blob/main/Troubleshooting.md Illustrates a MalformedJsonException message indicating the location of a syntax error in JSON data, specifically a trailing comma, using line and column numbers and JSONPath. ```APIDOC MalformedJsonException: Use JsonReader.setStrictness(Strictness.LENIENT) to accept malformed JSON at line 5 column 4 path $.languages[2] ``` -------------------------------- ### Gson Array Serialization and Deserialization Source: https://github.com/google/gson/blob/main/UserGuide.md Shows how Gson handles the serialization of Java arrays (including multi-dimensional arrays) into JSON arrays and the deserialization of JSON arrays back into Java arrays. ```java Gson gson = new Gson(); int[] ints = {1, 2, 3, 4, 5}; String[] strings = {"abc", "def", "ghi"}; // Serialization gson.toJson(ints); // ==> [1,2,3,4,5] gson.toJson(strings); // ==> ["abc", "def", "ghi"] // Deserialization int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); // ==> ints2 will be same as ints ``` -------------------------------- ### Gson Handling of Inner Classes Source: https://github.com/google/gson/blob/main/UserGuide.md Explains Gson's limitations with serializing and deserializing non-static inner classes due to the implicit reference to the outer class. It provides a workaround using a custom InstanceCreator. ```java public class A { public String a; class B { public String b; public B() { // No args constructor for B } } } // NOTE: The above class B can not (by default) be serialized with Gson. // Gson can not deserialize {"b":"abc"} into an instance of B since the class B is an inner class. // If it was defined as static class B then Gson would have been able to deserialize the string. // Another solution is to write a custom instance creator for B. public class InstanceCreatorForB implements InstanceCreator { private final A a; public InstanceCreatorForB(A a) { this.a = a; } public A.B createInstance(Type type) { return a.new B(); } } // The above is possible, but not recommended. ``` -------------------------------- ### GsonBuilder Configuration for Default Field Values Source: https://github.com/google/gson/blob/main/Troubleshooting.md Illustrates how to configure `GsonBuilder` to disable the use of JDK `Unsafe` for creating instances when a no-args constructor is missing. This helps in identifying issues where default field values are not being set correctly after deserialization. ```java Gson gson = new GsonBuilder().disableJdkUnsafe().create(); ``` -------------------------------- ### Gson Map Serialization (String and Integer Keys) Source: https://github.com/google/gson/blob/main/UserGuide.md Demonstrates Gson's default serialization of `java.util.Map` implementations. String keys are used directly, and non-string keys are converted to strings via `toString()`. Null keys are serialized as 'null'. ```java Gson gson = new Gson(); Map stringMap = new LinkedHashMap<>(); stringMap.put("key", "value"); stringMap.put(null, "null-entry"); // Serialization String json = gson.toJson(stringMap); // ==> {"key":"value","null":"null-entry"} Map intMap = new LinkedHashMap<>(); intMap.put(2, 4); intMap.put(3, 6); // Serialization String json = gson.toJson(intMap); // ==> {"2":4,"3":6} ``` -------------------------------- ### Gson Custom Type Adapter Issues Source: https://github.com/google/gson/blob/main/Troubleshooting.md Addresses problems where Gson fails to use registered custom TypeAdapters, Serializers, or Deserializers. It covers incorrect type registration, subclass handling, and ensuring the correct Gson instance is used. It also highlights the difference between `registerTypeAdapter` and `registerTypeHierarchyAdapter` and advises on handling parameterized types and primitive wrappers. ```java GsonBuilder builder = new GsonBuilder(); // Register adapter for MyClass binder.registerTypeAdapter(MyClass.class, new MyClassAdapter()); // To also handle subclasses, use registerTypeHierarchyAdapter // builder.registerTypeHierarchyAdapter(MyBaseClass.class, new MyBaseClassAdapter()); Gson gson = builder.create(); ``` ```java import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; // Example of a TypeAdapterFactory for parameterized types public class MyListTypeAdapterFactory implements TypeAdapterFactory { @Override public TypeAdapter create(Gson gson, TypeToken type) { if (type.getType() instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type.getType(); Type rawType = parameterizedType.getRawType(); if (rawType.equals(List.class)) { // Handle List or other specific parameterized types // Return a custom TypeAdapter for List } } return null; // Let Gson handle other types } } ``` -------------------------------- ### Gson Object Serialization and Deserialization Source: https://github.com/google/gson/blob/main/UserGuide.md Illustrates the process of serializing a custom Java object into a JSON string and deserializing a JSON string back into an instance of the custom object using Gson. It highlights the handling of fields, including transient fields and nulls. ```java class BagOfPrimitives { private int value1 = 1; private String value2 = "abc"; private transient int value3 = 3; BagOfPrimitives() { // no-args constructor } } // 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); // ==> obj2 is just like obj ``` -------------------------------- ### Gson with Android R8/ProGuard Source: https://github.com/google/gson/blob/main/Troubleshooting.md Discusses Gson's compatibility with Android's R8/ProGuard minification. Provides strategies to ensure Gson works correctly, including constraining reflected classes by using no-arg constructors and `@SerializedName`, or avoiding reflection entirely by using `TypeAdapter` or `JsonReader`/`JsonWriter`. ```java // Constrain reflected classes: // Ensure no-arg constructors and use @SerializedName // Avoid Reflection: // Use GsonBuilder.addReflectionAccessFilter() GsonBuilder builder = new GsonBuilder(); builder.addReflectionAccessFilter(type -> Gson.ReflectionAccessFilter.Block.BLOCK_ALL); Gson gson = builder.create(); ``` ```APIDOC GsonBuilder: addReflectionAccessFilter(ReflectionAccessFilter filter) Adds a filter that controls Gson's access to fields and methods via reflection. Parameters: filter: A ReflectionAccessFilter instance. Example Filter: type -> Gson.ReflectionAccessFilter.Block.BLOCK_ALL ``` -------------------------------- ### Gson Built-in Type Adapters Source: https://github.com/google/gson/blob/main/UserGuide.md Highlights Gson's built-in support for serializing and deserializing common Java types like java.net.URL and java.net.URI, which have default representations that might not be ideal. For a comprehensive list, refer to the internal TypeAdapters class. ```java // Gson has built-in support for: // java.net.URL to match strings like "https://github.com/google/gson/" // java.net.URI to match strings like "/google/gson/" // For more, see: gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java ``` -------------------------------- ### Output Gson Field Naming JSON Source: https://github.com/google/gson/blob/main/UserGuide.md This JSON snippet displays the output of serializing `SomeObject` using the naming strategies defined in the corresponding Java code. It confirms that `@SerializedName` overrides policies and that the policy applies to other fields. ```JSON {"custom_naming":"first","SomeOtherField":"second"} ``` -------------------------------- ### Gson Generic Type Serialization with TypeToken Source: https://github.com/google/gson/blob/main/UserGuide.md Demonstrates how to use Gson to serialize and deserialize generic types by employing the TypeToken class to preserve generic type information lost during Java's type erasure. This is crucial for Gson to correctly handle generic fields. ```java class Foo { T value; } // Example usage: Gson gson = new Gson(); Foo foo = new Foo(); // Serialization: gson.toJson(foo); // Deserialization: gson.fromJson(json, foo.getClass()); // Fails without TypeToken // Corrected approach using TypeToken: Type fooType = new TypeToken>() {}.getType(); gson.toJson(foo, fooType); gson.fromJson(json, fooType); ``` -------------------------------- ### Gson: Handling Malformed JSON with Trailing Commas Source: https://github.com/google/gson/blob/main/Troubleshooting.md Demonstrates how malformed JSON with trailing commas causes parsing errors and how to identify the issue using exception messages and JSONPath. It also suggests fixing the JSON data or using lenient parsing. ```json { "languages": [ "English", "French", ] } ``` -------------------------------- ### Running Benchmarks on Android with Vogar Source: https://github.com/google/gson/blob/main/ReleaseProcess.md Instructions for executing benchmarks on an Android device using the Vogar tool. This includes setting up the environment variables for ADB and Vogar, and specifying the benchmark class and VM options. ```bash vogar --benchmark --classpath gson.jar path/to/Benchmark.java ``` ```bash export ANDROID_HOME=~/apps/android-sdk-mac_x86 export PATH=$PATH:$ANDROID_HOME/platform-tools/:$ANDROID_HOME/android-sdk-mac_x86/tools/ $VOGAR_HOME/bin/vogar \ --benchmark \ --sourcepath ../gson/src/main/java/ \ src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java \ -- \ --vm "app_process -Xgc:noconcurrent,app_process" ``` -------------------------------- ### Custom TypeAdapter for Safe Class Serialization in Gson Source: https://github.com/google/gson/blob/main/Troubleshooting.md Provides a solution for UnsupportedOperationException when serializing/deserializing java.lang.Class. Gson intentionally disallows this for security reasons. The solution involves using a custom TypeAdapter to serialize Class objects as string aliases and then mapping them back, ensuring only subclasses of a common base class are loaded. ```java import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; public class SafeClassTypeAdapter extends TypeAdapter> { private static final String BASE_CLASS_NAME = "com.example.MyBaseClass"; // Replace with your actual base class @Override public void write(JsonWriter out, Class value) throws IOException { if (value == null) { out.nullValue(); } else { out.value(value.getName()); } } @Override public Class read(JsonReader in) throws IOException { if (in.peek() == com.google.gson.stream.JsonToken.NULL) { in.nextNull(); return null; } String className = in.nextString(); try { // Load class safely, ensuring it's a subclass of MyBaseClass Class loadedClass = Class.forName(className, false, getClass().getClassLoader()); Class baseClass = Class.forName(BASE_CLASS_NAME, false, getClass().getClassLoader()); return loadedClass.asSubclass(baseClass); } catch (ClassNotFoundException | ClassCastException e) { throw new IOException("Failed to load or cast class: " + className, e); } } } // Usage with GsonBuilder: // Gson gson = new GsonBuilder() // .registerTypeAdapter(Class.class, new SafeClassTypeAdapter()) // .create(); ``` -------------------------------- ### TypeToken Exceptions with ProGuard/R8 Source: https://github.com/google/gson/blob/main/Troubleshooting.md Resolves `IllegalStateException: 'TypeToken must be created with a type argument'` or `RuntimeException: 'Missing type parameter'` errors. These typically occur when `TypeToken` is used without a type argument or when code shrinking tools like ProGuard/R8 are not configured correctly for Gson's reflection mechanisms. ```proguard # Keep generic signatures; needed for correct type resolution -keepattributes Signature # Keep class TypeToken (respectively its generic signature) -keep class com.google.gson.reflect.TypeToken { *; } # Keep any (anonymous) classes extending TypeToken -keep class * extends com.google.gson.reflect.TypeToken ``` -------------------------------- ### Add Android SDK Tools to PATH Source: https://github.com/google/gson/blob/main/ReleaseProcess.md Append the platform-tools and tools directories of the Android SDK to the system's PATH environment variable. This allows executing Android tools like 'adb' directly from the command line. ```bash export PATH=$PATH:$ANDROID_HOME/platform-tools/:$ANDROID_HOME/android-sdk-mac_x86/tools/ ``` -------------------------------- ### Prepare Maven Release (Local Testing Execution) Source: https://github.com/google/gson/blob/main/ReleaseProcess.md Initiate the Maven release prepare goal as part of the local testing process. This verifies that the preparation steps (version updates, tagging) work correctly with the local Git configuration. ```sh mvn release:prepare ``` -------------------------------- ### Handling Unexpected JSON Structure with Gson Source: https://github.com/google/gson/blob/main/Troubleshooting.md This section addresses IllegalStateExceptions in Gson when the JSON structure doesn't match the Java class model. It explains how to diagnose the issue using exception messages and JSONPath, and provides a solution by correcting the Java class to align with the JSON data, such as changing a String field to a List. ```java class WebPage { String languages; } ``` ```json { "languages": ["English", "French"] } ``` ```java class WebPage { List languages; } ``` -------------------------------- ### Run Collections Deserialization Benchmark on Android Source: https://github.com/google/gson/blob/main/ReleaseProcess.md Execute the CollectionsDeserializationBenchmark specifically on an Android device using Vogar. This command includes setting source path, specifying the benchmark class, and passing arguments to the Android VM. ```bash $VOGAR_HOME/bin/vogar \ --benchmark \ --sourcepath ../gson/src/main/java/ \ src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java \ -- \ --vm "app_process -Xgc:noconcurrent,app_process" ``` -------------------------------- ### Maven Release Preparation Source: https://github.com/google/gson/blob/main/ReleaseProcess.md Prepares for a Maven release by cleaning previous builds, preparing the release version, and tagging the release. It follows semantic versioning principles. ```bash cd gson mvn release:clean mvn release:prepare ``` -------------------------------- ### Gson Inner Interfaces Example Source: https://github.com/google/gson/blob/main/GsonDesignDocument.md Gson utilizes inner interfaces for contextual information, such as `JsonSerializer.Context` and `JsonDeserializer.Context`, as a stylistic choice. ```Java import com.google.gson.JsonDeserializer; public class MyDeserializer implements JsonDeserializer { @Override public MyObject deserialize(com.google.gson.JsonElement json, java.lang.reflect.Type typeOfT, JsonDeserializer.Context context) throws com.google.gson.JsonParseException { // Use context for advanced deserialization needs // Example: context.deserialize(json.getAsJsonObject().get("nestedObject"), AnotherObject.class); return null; // Placeholder } } ``` -------------------------------- ### Run Benchmark on Android with Vogar Source: https://github.com/google/gson/blob/main/ReleaseProcess.md Execute a specific Java benchmark class on an connected Android device or emulator using the Vogar tool. Requires the benchmark class and Gson JAR to be available and adb on the system's PATH. ```bash vogar --benchmark --classpath gson.jar path/to/Benchmark.java ``` -------------------------------- ### Perform Maven Release (Local Testing Execution) Source: https://github.com/google/gson/blob/main/ReleaseProcess.md Execute the Maven release perform goal in the local testing environment. This verifies that the build and deployment steps correctly place artifacts in the configured local Maven repository. ```sh mvn release:perform ``` -------------------------------- ### Excluding Static Fields in Gson Serialization Source: https://github.com/google/gson/blob/main/Troubleshooting.md Shows how to configure GsonBuilder to exclude static fields from JSON output by explicitly adding Modifier.STATIC to excludeFieldsWithModifiers. ```java Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .create(); ``` -------------------------------- ### Maven Build Command Source: https://github.com/google/gson/blob/main/test-shrinker/README.md Command to clean the project and run integration tests, ensuring the build process includes code shrinking and obfuscation. ```bash mvn clean verify ``` -------------------------------- ### Gson Community and Support Source: https://github.com/google/gson/blob/main/README.md Resources for discussing Gson, asking questions, and seeking support, including Stack Overflow, GitHub Discussions, and a Google Group. ```markdown ['gson' tag on StackOverflow](https://stackoverflow.com/questions/tagged/gson) ``` ```markdown [GitHub Discussions](https://github.com/google/gson/discussions) ``` ```markdown [google-gson Google group](https://groups.google.com/group/google-gson) ``` -------------------------------- ### Third-Party Gson Resources Source: https://github.com/google/gson/blob/main/README.md Links to external tutorials and API reports created by third parties to help users learn and understand Gson. ```markdown [Gson Tutorial](https://www.studytrails.com/java/json/java-google-json-introduction/) by `StudyTrails` ``` ```markdown [Gson Tutorial Series](https://futurestud.io/tutorials/gson-getting-started-with-java-json-serialization-deserialization) by `Future Studio` ``` ```markdown [Gson API Report](https://abi-laboratory.pro/java/tracker/timeline/gson/) ``` -------------------------------- ### Custom JsonDeserializer for DateTime Source: https://github.com/google/gson/blob/main/UserGuide.md Illustrates a custom JsonDeserializer for the JodaTime DateTime class. The deserialize method parses a JSON string and converts it back into a DateTime object. ```java private class DateTimeDeserializer implements JsonDeserializer { public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new DateTime(json.getAsJsonPrimitive().getAsString()); } } ``` -------------------------------- ### Gson Contribution Guidelines Source: https://github.com/google/gson/blob/main/README.md Information on how to contribute to the Gson project, including searching for existing issues and discussing new features. ```markdown [contributing guide](https://github.com/google/.github/blob/master/CONTRIBUTING.md) ``` -------------------------------- ### Build Gson with Maven Source: https://github.com/google/gson/blob/main/README.md Instructions on how to build the Gson project using Maven. Requires JDK 11 or newer, with JDK 17 or 21 recommended for building. ```bash mvn clean verify ``` -------------------------------- ### GitHub Release Creation Source: https://github.com/google/gson/blob/main/ReleaseProcess.md Steps for creating a new release on GitHub, including automatically generating release notes and manually editing them to highlight key changes. ```plaintext Create a GitHub release for the new version. You can let GitHub automatically generate the description for the release, but you should edit it manually to point out the most important changes and potentially incompatible changes. ``` -------------------------------- ### Gson Releases and Changelog Source: https://github.com/google/gson/blob/main/README.md Information on the latest releases and changes in Gson versions, with a link to the GitHub releases page and the local CHANGELOG.md for older versions. ```markdown [Releases and change log](https://github.com/google/gson/releases) ``` ```markdown [`CHANGELOG.md`](CHANGELOG.md) ``` -------------------------------- ### Serializing Null Values in JSON Source: https://github.com/google/gson/blob/main/UserGuide.md Enables Gson to include null fields in the JSON output. This is done using the GsonBuilder and the serializeNulls() method. Null values are represented as JsonNull elements. ```java Gson gson = new GsonBuilder().serializeNulls().create(); ``` -------------------------------- ### Updating Version References Source: https://github.com/google/gson/blob/main/ReleaseProcess.md Manual verification of version references in project files like README.md and UserGuide.md after a release, ensuring automatic replacements by Maven are correct. ```plaintext Update version references in: - README.md - UserGuide.md Note: When using the Maven Release Plugin as described above, these version references should have been replaced automatically, but verify this manually nonetheless to be on the safe side. ```