A Retrofit Converter for Java's scalar value types
npx @tessl/cli install tessl/maven-com-squareup-retrofit2--converter-scalars@3.0.0Retrofit 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.
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-scalars</artifactId>
<version>3.0.0</version>
</dependency>implementation 'com.squareup.retrofit2:converter-scalars:3.0.0'import retrofit2.converter.scalars.ScalarsConverterFactory;import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.Call;
// Create Retrofit instance with ScalarsConverterFactory
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(ScalarsConverterFactory.create())
.build();
// Define service interface using scalar types
interface ApiService {
@POST("message")
Call<String> sendMessage(@Body String message);
@GET("count")
Call<Integer> getCount();
@POST("status")
Call<Boolean> updateStatus(@Body Boolean enabled);
}
// Use the service
ApiService service = retrofit.create(ApiService.class);
Call<String> call = service.sendMessage("Hello World");The converter is built around the Retrofit converter factory pattern:
ScalarsConverterFactory implements Converter.Factory to provide type-specific convertersScalarRequestBodyConverter handles all scalar-to-RequestBody conversionstext/plain; charset=UTF-8 for request bodiesCreates and manages converters for scalar types in Retrofit.
public final class ScalarsConverterFactory extends Converter.Factory {
/**
* Creates a new instance of the converter factory
* @return ScalarsConverterFactory instance
*/
public static ScalarsConverterFactory create();
/**
* Returns a converter for converting objects to RequestBody
* @param type the type to convert from
* @param parameterAnnotations annotations on the parameter
* @param methodAnnotations annotations on the method
* @param retrofit the Retrofit instance
* @return Converter instance for supported types, null otherwise
*/
@Nullable
public Converter<?, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit
);
/**
* Returns a converter for converting ResponseBody to objects
* @param type the type to convert to
* @param annotations annotations on the method
* @param retrofit the Retrofit instance
* @return Converter instance for supported types, null otherwise
*/
@Nullable
public Converter<ResponseBody, ?> responseBodyConverter(
Type type,
Annotation[] annotations,
Retrofit retrofit
);
}The converter supports bidirectional conversion for the following Java types:
java.lang.Stringtext/plain RequestBodyboolean, java.lang.BooleanBoolean.valueOf()byte/Byte, short/Short, int/Integer, long/Long, float/Float, double/DoubleString.valueOf()valueOf() methodschar, java.lang.CharacterIOException with message "Expected body of length 1 for Character conversion but was N" if response body length is not exactly 1// Core Retrofit types used by the converter
import retrofit2.Converter;
import retrofit2.Retrofit;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.MediaType;
// Standard Java types
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;
import java.io.IOException;
import javax.annotation.Nullable;The converter may throw the following exceptions:
IOException: During conversion operations, particularly:
NumberFormatException: When parsing numeric types from malformed string content (thrown by wrapper class valueOf() methods)Usage Examples:
// Handle potential conversion errors
try {
Call<Integer> call = service.getNumber();
Response<Integer> response = call.execute();
if (response.isSuccessful()) {
Integer value = response.body(); // May be null
}
} catch (IOException e) {
// Handle network or conversion errors
}
// Character conversion with error handling
interface CharService {
@GET("initial")
Call<Character> getInitial();
}
// This will throw IOException if response is not exactly 1 character
// For example, if API returns "AB" or empty stringtext/plain; charset=UTF-8 RequestBodyService Interface Examples:
interface ScalarApiService {
// String endpoints
@POST("echo")
Call<String> echo(@Body String message);
// Boolean endpoints
@POST("toggle")
Call<Boolean> toggle(@Body Boolean state);
// Numeric endpoints
@GET("temperature")
Call<Double> getTemperature();
@POST("quantity")
Call<Void> setQuantity(@Body Integer count);
// Character endpoint
@GET("grade")
Call<Character> getGrade();
}Multiple Converter Integration:
// Use with other converters (order matters)
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(ScalarsConverterFactory.create()) // Scalars first
.addConverterFactory(GsonConverterFactory.create()) // JSON for complex objects
.build();