A Retrofit converter that uses Moshi for JSON serialization and deserialization.
npx @tessl/cli install tessl/maven-com-squareup-retrofit2--converter-moshi@3.0.00
# Retrofit Moshi Converter
1
2
A Retrofit converter factory that uses Square's Moshi library for JSON serialization and deserialization. This converter enables type-safe conversion between Java objects and JSON for HTTP requests and responses in Retrofit 2 applications.
3
4
## Package Information
5
6
- **Package Name**: converter-moshi
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**: Add to your `build.gradle`:
10
11
```gradle
12
implementation 'com.squareup.retrofit2:converter-moshi:3.0.0'
13
```
14
15
Maven:
16
17
```xml
18
<dependency>
19
<groupId>com.squareup.retrofit2</groupId>
20
<artifactId>converter-moshi</artifactId>
21
<version>3.0.0</version>
22
</dependency>
23
```
24
25
## Core Imports
26
27
```java
28
import retrofit2.converter.moshi.MoshiConverterFactory;
29
import com.squareup.moshi.Moshi;
30
import retrofit2.Retrofit;
31
```
32
33
## Basic Usage
34
35
```java
36
import retrofit2.converter.moshi.MoshiConverterFactory;
37
import retrofit2.Retrofit;
38
import com.squareup.moshi.Moshi;
39
40
// Basic setup with default Moshi configuration
41
Retrofit retrofit = new Retrofit.Builder()
42
.baseUrl("https://api.example.com/")
43
.addConverterFactory(MoshiConverterFactory.create())
44
.build();
45
46
// Advanced setup with custom Moshi instance
47
Moshi moshi = new Moshi.Builder()
48
.add(new DateAdapter())
49
.build();
50
51
Retrofit retrofit = new Retrofit.Builder()
52
.baseUrl("https://api.example.com/")
53
.addConverterFactory(MoshiConverterFactory.create(moshi))
54
.build();
55
56
// Configuration options
57
Retrofit retrofit = new Retrofit.Builder()
58
.baseUrl("https://api.example.com/")
59
.addConverterFactory(
60
MoshiConverterFactory.create(moshi)
61
.asLenient()
62
.failOnUnknown()
63
.withNullSerialization()
64
.withStreaming()
65
)
66
.build();
67
```
68
69
## Architecture
70
71
The Moshi converter integrates with Retrofit's converter factory system:
72
73
- **Factory Pattern**: `MoshiConverterFactory` creates appropriate converters for each request/response type
74
- **Type Safety**: Uses Moshi's `JsonAdapter<T>` system for compile-time type checking
75
- **Annotation Support**: Automatically handles Moshi's `@JsonQualifier` annotations
76
- **Configuration Chain**: Immutable builder pattern for customizing JSON processing behavior
77
- **Streaming Support**: Optional streaming serialization for large request bodies
78
79
## Capabilities
80
81
### Factory Creation
82
83
Creates `MoshiConverterFactory` instances with default or custom Moshi configurations.
84
85
```java { .api }
86
/**
87
* Create an instance using a default Moshi instance for conversion.
88
*/
89
public static MoshiConverterFactory create();
90
91
/**
92
* Create an instance using the provided Moshi instance for conversion.
93
* @param moshi The Moshi instance to use for JSON processing
94
* @throws NullPointerException if moshi is null
95
*/
96
public static MoshiConverterFactory create(Moshi moshi);
97
```
98
99
### Configuration Methods
100
101
Customize JSON processing behavior through method chaining. Each method returns a new factory instance.
102
103
```java { .api }
104
/**
105
* Return a new factory which uses lenient adapters that are tolerant of malformed JSON.
106
*/
107
public MoshiConverterFactory asLenient();
108
109
/**
110
* Return a new factory which uses adapters that fail when encountering unknown JSON properties.
111
*/
112
public MoshiConverterFactory failOnUnknown();
113
114
/**
115
* Return a new factory which includes null values in the serialized JSON output.
116
*/
117
public MoshiConverterFactory withNullSerialization();
118
119
/**
120
* Return a new factory which streams serialization of request messages to bytes on the HTTP thread.
121
* This is either the calling thread for Call.execute(), or one of OkHttp's background threads
122
* for Call.enqueue(). Response bytes are always converted on OkHttp's background threads.
123
*/
124
public MoshiConverterFactory withStreaming();
125
```
126
127
### Converter Creation
128
129
Internal methods that Retrofit calls to create converters for specific types. You typically don't call these directly.
130
131
```java { .api }
132
/**
133
* Creates a converter for response bodies of the specified type.
134
* @param type The type to convert to
135
* @param annotations Annotations on the method
136
* @param retrofit The Retrofit instance
137
* @return A converter for ResponseBody to the specified type, or null if not handled
138
*/
139
public Converter<ResponseBody, ?> responseBodyConverter(
140
Type type,
141
Annotation[] annotations,
142
Retrofit retrofit
143
);
144
145
/**
146
* Creates a converter for request bodies of the specified type.
147
* @param type The type to convert from
148
* @param parameterAnnotations Annotations on the parameter
149
* @param methodAnnotations Annotations on the method
150
* @param retrofit The Retrofit instance
151
* @return A converter from the specified type to RequestBody, or null if not handled
152
*/
153
public Converter<?, RequestBody> requestBodyConverter(
154
Type type,
155
Annotation[] parameterAnnotations,
156
Annotation[] methodAnnotations,
157
Retrofit retrofit
158
);
159
```
160
161
## Types
162
163
```java { .api }
164
/**
165
* The main converter factory class that extends Retrofit's Converter.Factory.
166
* Instances are immutable and thread-safe.
167
*/
168
public final class MoshiConverterFactory extends Converter.Factory {
169
// Factory methods and configuration methods as documented above
170
}
171
```
172
173
## Error Handling
174
175
The converter can throw the following exceptions:
176
177
- **`JsonDataException`**: Thrown by Moshi when JSON is malformed or when `failOnUnknown()` is enabled and unknown properties are encountered
178
- **`IOException`**: Thrown during I/O operations when reading response bodies or writing request bodies
179
- **`NullPointerException`**: Thrown when a null `Moshi` instance is passed to `create(Moshi)`
180
181
```java
182
// Example error handling
183
try {
184
MyObject obj = apiService.getData().execute().body();
185
} catch (JsonDataException e) {
186
// Handle malformed JSON or unknown properties
187
System.err.println("JSON parsing error: " + e.getMessage());
188
} catch (IOException e) {
189
// Handle network or I/O errors
190
System.err.println("Network error: " + e.getMessage());
191
}
192
```
193
194
## Integration Notes
195
196
### Retrofit Configuration
197
198
- **Converter Order**: Add `MoshiConverterFactory` last in the converter chain as it handles all types by default
199
- **JsonQualifier Support**: Method and parameter annotations marked with `@JsonQualifier` are automatically used for adapter selection
200
- **Type Erasure**: Generic type information is preserved through Retrofit's `Type` parameter system
201
202
### Moshi Integration
203
204
- **Custom Adapters**: Configure custom `JsonAdapter` instances through the `Moshi.Builder`
205
- **Reflection**: Works with Moshi's reflection-based adapters for POJOs
206
- **Code Generation**: Compatible with Moshi's code generation for optimal performance
207
208
### Performance Considerations
209
210
- **Streaming**: Use `withStreaming()` for large request bodies to reduce memory usage
211
- **Thread Safety**: All factory instances are immutable and thread-safe
212
- **Adapter Caching**: Moshi adapters are cached internally for reuse across requests
213
214
### Requirements
215
216
- **Java**: Requires Java 8+ or Android API 21+
217
- **Dependencies**: Requires `retrofit2` and `com.squareup.moshi:moshi`
218
- **Optional**: `com.google.code.findbugs:jsr305` for additional annotations (compile-only)