0
# Retrofit Scalars Converter
1
2
Retrofit Scalars Converter provides automatic conversion between Java scalar types (String, primitives, and their boxed counterparts) and HTTP request/response bodies with `text/plain` content type. It enables seamless handling of simple scalar values in Retrofit API definitions without requiring custom serialization logic.
3
4
## Package Information
5
6
- **Package Name**: converter-scalars
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Group ID**: com.squareup.retrofit2
10
- **Artifact ID**: converter-scalars
11
- **Installation**:
12
```xml
13
<dependency>
14
<groupId>com.squareup.retrofit2</groupId>
15
<artifactId>converter-scalars</artifactId>
16
<version>3.0.0</version>
17
</dependency>
18
```
19
Gradle:
20
```groovy
21
implementation 'com.squareup.retrofit2:converter-scalars:3.0.0'
22
```
23
24
## Core Imports
25
26
```java
27
import retrofit2.converter.scalars.ScalarsConverterFactory;
28
```
29
30
## Basic Usage
31
32
```java
33
import retrofit2.Retrofit;
34
import retrofit2.converter.scalars.ScalarsConverterFactory;
35
import retrofit2.http.Body;
36
import retrofit2.http.GET;
37
import retrofit2.http.POST;
38
import retrofit2.Call;
39
40
// Create Retrofit instance with ScalarsConverterFactory
41
Retrofit retrofit = new Retrofit.Builder()
42
.baseUrl("https://api.example.com/")
43
.addConverterFactory(ScalarsConverterFactory.create())
44
.build();
45
46
// Define service interface using scalar types
47
interface ApiService {
48
@POST("message")
49
Call<String> sendMessage(@Body String message);
50
51
@GET("count")
52
Call<Integer> getCount();
53
54
@POST("status")
55
Call<Boolean> updateStatus(@Body Boolean enabled);
56
}
57
58
// Use the service
59
ApiService service = retrofit.create(ApiService.class);
60
Call<String> call = service.sendMessage("Hello World");
61
```
62
63
## Architecture
64
65
The converter is built around the Retrofit converter factory pattern:
66
67
- **Factory Pattern**: `ScalarsConverterFactory` implements `Converter.Factory` to provide type-specific converters
68
- **Request Conversion**: Single `ScalarRequestBodyConverter` handles all scalar-to-RequestBody conversions
69
- **Response Conversion**: Individual converters for each scalar type handle ResponseBody-to-scalar conversions
70
- **Type Safety**: Strict type checking with support for both primitive and boxed types
71
- **Content Type**: Uses `text/plain; charset=UTF-8` for request bodies
72
73
## Capabilities
74
75
### Converter Factory
76
77
Creates and manages converters for scalar types in Retrofit.
78
79
```java { .api }
80
public final class ScalarsConverterFactory extends Converter.Factory {
81
/**
82
* Creates a new instance of the converter factory
83
* @return ScalarsConverterFactory instance
84
*/
85
public static ScalarsConverterFactory create();
86
87
/**
88
* Returns a converter for converting objects to RequestBody
89
* @param type the type to convert from
90
* @param parameterAnnotations annotations on the parameter
91
* @param methodAnnotations annotations on the method
92
* @param retrofit the Retrofit instance
93
* @return Converter instance for supported types, null otherwise
94
*/
95
@Nullable
96
public Converter<?, RequestBody> requestBodyConverter(
97
Type type,
98
Annotation[] parameterAnnotations,
99
Annotation[] methodAnnotations,
100
Retrofit retrofit
101
);
102
103
/**
104
* Returns a converter for converting ResponseBody to objects
105
* @param type the type to convert to
106
* @param annotations annotations on the method
107
* @param retrofit the Retrofit instance
108
* @return Converter instance for supported types, null otherwise
109
*/
110
@Nullable
111
public Converter<ResponseBody, ?> responseBodyConverter(
112
Type type,
113
Annotation[] annotations,
114
Retrofit retrofit
115
);
116
}
117
```
118
119
### Supported Scalar Types
120
121
The converter supports bidirectional conversion for the following Java types:
122
123
#### String Type
124
- **Type**: `java.lang.String`
125
- **Request Conversion**: Converts String to `text/plain` RequestBody
126
- **Response Conversion**: Extracts string content from ResponseBody
127
128
#### Boolean Types
129
- **Types**: `boolean`, `java.lang.Boolean`
130
- **Request Conversion**: Converts to string representation ("true"/"false")
131
- **Response Conversion**: Parses string using `Boolean.valueOf()`
132
133
#### Numeric Primitive Types
134
- **Types**: `byte`/`Byte`, `short`/`Short`, `int`/`Integer`, `long`/`Long`, `float`/`Float`, `double`/`Double`
135
- **Request Conversion**: Converts to string representation using `String.valueOf()`
136
- **Response Conversion**: Parses string using respective wrapper class `valueOf()` methods
137
138
#### Character Types
139
- **Types**: `char`, `java.lang.Character`
140
- **Request Conversion**: Converts character to single-character string
141
- **Response Conversion**: Extracts first character from response body string
142
- **Error Handling**: Throws `IOException` with message "Expected body of length 1 for Character conversion but was N" if response body length is not exactly 1
143
144
## Types
145
146
```java { .api }
147
// Core Retrofit types used by the converter
148
import retrofit2.Converter;
149
import retrofit2.Retrofit;
150
import okhttp3.RequestBody;
151
import okhttp3.ResponseBody;
152
import okhttp3.MediaType;
153
154
// Standard Java types
155
import java.lang.reflect.Type;
156
import java.lang.annotation.Annotation;
157
import java.io.IOException;
158
import javax.annotation.Nullable;
159
```
160
161
## Error Handling
162
163
The converter may throw the following exceptions:
164
165
- **`IOException`**: During conversion operations, particularly:
166
- Character conversion when response body length is not exactly 1
167
- Network or I/O errors when reading response body content
168
- **`NumberFormatException`**: When parsing numeric types from malformed string content (thrown by wrapper class `valueOf()` methods)
169
170
**Usage Examples:**
171
172
```java
173
// Handle potential conversion errors
174
try {
175
Call<Integer> call = service.getNumber();
176
Response<Integer> response = call.execute();
177
if (response.isSuccessful()) {
178
Integer value = response.body(); // May be null
179
}
180
} catch (IOException e) {
181
// Handle network or conversion errors
182
}
183
184
// Character conversion with error handling
185
interface CharService {
186
@GET("initial")
187
Call<Character> getInitial();
188
}
189
190
// This will throw IOException if response is not exactly 1 character
191
// For example, if API returns "AB" or empty string
192
```
193
194
## Content Type Details
195
196
- **Request Bodies**: All scalar values are converted to `text/plain; charset=UTF-8` RequestBody
197
- **Response Bodies**: Converter accepts any response content type and attempts to parse the body as a string
198
- **Encoding**: UTF-8 encoding is used for all text conversion operations
199
200
## Integration Patterns
201
202
**Service Interface Examples:**
203
204
```java
205
interface ScalarApiService {
206
// String endpoints
207
@POST("echo")
208
Call<String> echo(@Body String message);
209
210
// Boolean endpoints
211
@POST("toggle")
212
Call<Boolean> toggle(@Body Boolean state);
213
214
// Numeric endpoints
215
@GET("temperature")
216
Call<Double> getTemperature();
217
218
@POST("quantity")
219
Call<Void> setQuantity(@Body Integer count);
220
221
// Character endpoint
222
@GET("grade")
223
Call<Character> getGrade();
224
}
225
```
226
227
**Multiple Converter Integration:**
228
229
```java
230
// Use with other converters (order matters)
231
Retrofit retrofit = new Retrofit.Builder()
232
.baseUrl("https://api.example.com/")
233
.addConverterFactory(ScalarsConverterFactory.create()) // Scalars first
234
.addConverterFactory(GsonConverterFactory.create()) // JSON for complex objects
235
.build();
236
```