A Retrofit Converter which uses Gson for serialization to and from JSON
npx @tessl/cli install tessl/maven-com-squareup-retrofit2--converter-gson@3.0.00
# Retrofit2 Gson Converter
1
2
A Retrofit Converter which uses Gson for serialization to and from JSON. This converter provides seamless integration between Retrofit's HTTP client functionality and Google's Gson library for JSON processing.
3
4
## Package Information
5
6
- **Package Name**: converter-gson
7
- **Group ID**: com.squareup.retrofit2
8
- **Package Type**: Maven
9
- **Language**: Java
10
- **Installation**:
11
```xml
12
<dependency>
13
<groupId>com.squareup.retrofit2</groupId>
14
<artifactId>converter-gson</artifactId>
15
<version>3.0.0</version>
16
</dependency>
17
```
18
19
Gradle:
20
```groovy
21
implementation 'com.squareup.retrofit2:converter-gson:3.0.0'
22
```
23
24
## Core Imports
25
26
```java
27
import retrofit2.converter.gson.GsonConverterFactory;
28
import com.google.gson.Gson;
29
import retrofit2.Retrofit;
30
```
31
32
## Basic Usage
33
34
```java
35
import retrofit2.converter.gson.GsonConverterFactory;
36
import retrofit2.Retrofit;
37
import com.google.gson.Gson;
38
import com.google.gson.GsonBuilder;
39
import com.google.gson.FieldNamingPolicy;
40
41
// Basic usage with default Gson configuration
42
Retrofit retrofit = new Retrofit.Builder()
43
.baseUrl("https://api.example.com/")
44
.addConverterFactory(GsonConverterFactory.create())
45
.build();
46
47
// Usage with custom Gson instance
48
Gson customGson = new GsonBuilder()
49
.setDateFormat("yyyy-MM-dd HH:mm:ss")
50
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
51
.create();
52
53
Retrofit retrofitWithCustomGson = new Retrofit.Builder()
54
.baseUrl("https://api.example.com/")
55
.addConverterFactory(GsonConverterFactory.create(customGson))
56
.build();
57
58
// Enable streaming for large request bodies
59
Retrofit streamingRetrofit = new Retrofit.Builder()
60
.baseUrl("https://api.example.com/")
61
.addConverterFactory(GsonConverterFactory.create().withStreaming())
62
.build();
63
```
64
65
## Architecture
66
67
The Gson converter consists of the main factory class and internal converter implementations:
68
69
- **GsonConverterFactory**: Main factory class that creates request and response body converters
70
- **GsonRequestBodyConverter**: Package-private converter that handles Java object to JSON request body conversion
71
- **GsonResponseBodyConverter**: Package-private converter that handles JSON response body to Java object conversion
72
- **GsonStreamingRequestBody**: Streaming request body implementation that writes JSON directly to HTTP thread without buffering
73
- **Streaming Support**: Optional streaming mode that prevents memory buffering by writing JSON directly during HTTP transmission
74
- **UTF-8 Encoding**: Consistent UTF-8 encoding for all JSON operations
75
76
## Capabilities
77
78
### Converter Factory Creation
79
80
Creates converter factory instances with various configuration options.
81
82
```java { .api }
83
/**
84
* A converter factory which uses Gson for JSON serialization/deserialization.
85
* This factory should be added last to allow other converters to handle their types first.
86
*/
87
public final class GsonConverterFactory extends Converter.Factory {
88
89
/**
90
* Create an instance using a default Gson instance for conversion.
91
* Encoding to JSON and decoding from JSON (when no charset is specified by a header) will use UTF-8.
92
*
93
* @return GsonConverterFactory instance with default Gson configuration
94
*/
95
public static GsonConverterFactory create();
96
97
/**
98
* Create an instance using the provided Gson instance for conversion.
99
* Encoding to JSON and decoding from JSON (when no charset is specified by a header) will use UTF-8.
100
*
101
* @param gson The Gson instance to use for conversion (must not be null)
102
* @return GsonConverterFactory instance with custom Gson configuration
103
* @throws NullPointerException if gson is null
104
*/
105
public static GsonConverterFactory create(Gson gson);
106
107
/**
108
* Return a new factory which streams serialization of request messages to bytes on the HTTP thread.
109
* This is either the calling thread for Call.execute(), or one of OkHttp's background threads for Call.enqueue().
110
* Response bytes are always converted to message instances on one of OkHttp's background threads.
111
*
112
* Streaming prevents buffering of the entire JSON in memory by writing directly to the HTTP stream.
113
*
114
* @return GsonConverterFactory instance with streaming enabled
115
*/
116
public GsonConverterFactory withStreaming();
117
}
118
```
119
120
**Usage Examples:**
121
122
```java
123
// Default factory with built-in Gson configuration
124
GsonConverterFactory factory = GsonConverterFactory.create();
125
126
// Custom factory with specific Gson settings
127
Gson gson = new GsonBuilder()
128
.setDateFormat("yyyy-MM-dd")
129
.excludeFieldsWithoutExposeAnnotation()
130
.create();
131
GsonConverterFactory customFactory = GsonConverterFactory.create(gson);
132
133
// Enable streaming for large request bodies
134
GsonConverterFactory streamingFactory = GsonConverterFactory.create()
135
.withStreaming();
136
137
// Combine custom Gson with streaming
138
GsonConverterFactory advancedFactory = GsonConverterFactory.create(customGson)
139
.withStreaming();
140
```
141
142
### Response Body Conversion
143
144
Automatically converts HTTP response bodies from JSON to Java objects using Gson's type system.
145
146
```java { .api }
147
/**
148
* Creates a converter for ResponseBody to specified type.
149
* Called automatically by Retrofit when processing API responses.
150
*
151
* @param type The target type for conversion
152
* @param annotations Method annotations
153
* @param retrofit The Retrofit instance
154
* @return Converter instance or null if this factory cannot handle the type
155
*/
156
public Converter<ResponseBody, ?> responseBodyConverter(
157
Type type,
158
Annotation[] annotations,
159
Retrofit retrofit
160
);
161
```
162
163
### Request Body Conversion
164
165
Automatically converts Java objects to JSON request bodies using Gson serialization.
166
167
```java { .api }
168
/**
169
* Creates a converter for specified type to RequestBody.
170
* Called automatically by Retrofit when processing API requests.
171
*
172
* @param type The source type for conversion
173
* @param parameterAnnotations Parameter annotations
174
* @param methodAnnotations Method annotations
175
* @param retrofit The Retrofit instance
176
* @return Converter instance or null if this factory cannot handle the type
177
*/
178
public Converter<?, RequestBody> requestBodyConverter(
179
Type type,
180
Annotation[] parameterAnnotations,
181
Annotation[] methodAnnotations,
182
Retrofit retrofit
183
);
184
```
185
186
## Types
187
188
```java { .api }
189
// Standard Retrofit and Gson types used by the converter
190
import retrofit2.Converter;
191
import retrofit2.Retrofit;
192
import com.google.gson.Gson;
193
import com.google.gson.TypeAdapter;
194
import com.google.gson.JsonIOException;
195
import com.google.gson.reflect.TypeToken;
196
import okhttp3.RequestBody;
197
import okhttp3.ResponseBody;
198
import okhttp3.MediaType;
199
import java.lang.reflect.Type;
200
import java.lang.annotation.Annotation;
201
import java.io.IOException;
202
```
203
204
## Error Handling
205
206
The converter handles several error conditions:
207
208
- **NullPointerException**: Thrown when null Gson instance is passed to `create(Gson)`
209
- **JsonIOException**: Thrown with message "JSON document was not fully consumed." when response JSON contains extra content after the expected object
210
- **Gson Serialization Errors**: Propagated from underlying Gson serialization/deserialization operations
211
- **IOException**: Propagated from underlying I/O operations during JSON processing
212
213
## Thread Safety
214
215
All components of the Gson converter are thread-safe:
216
217
- **GsonConverterFactory**: Immutable and can be shared across multiple Retrofit instances
218
- **Internal Converters**: Stateless and thread-safe for concurrent request processing
219
- **Gson Integration**: Leverages Gson's thread-safe TypeAdapter system
220
221
## Best Practices
222
223
1. **Factory Placement**: Add GsonConverterFactory last in the converter list to allow other converters to handle their specific types first
224
2. **Custom Gson Configuration**: Use custom Gson instances for specific serialization requirements (date formats, field naming, etc.)
225
3. **Streaming Mode**: Enable streaming for applications that handle large request payloads to prevent memory buffering - JSON is written directly to the HTTP stream rather than being buffered in memory first
226
4. **Error Handling**: Handle JsonIOException and other Gson-related exceptions appropriately in your application
227
5. **UTF-8 Encoding**: The converter always uses UTF-8 encoding, which is the standard for JSON data