### 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