CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-squareup-retrofit2--converter-moshi

A Retrofit converter that uses Moshi for JSON serialization and deserialization.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Retrofit Moshi Converter

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.

Package Information

  • Package Name: converter-moshi
  • Package Type: maven
  • Language: Java
  • Installation: Add to your build.gradle:
implementation 'com.squareup.retrofit2:converter-moshi:3.0.0'

Maven:

<dependency>
  <groupId>com.squareup.retrofit2</groupId>
  <artifactId>converter-moshi</artifactId>
  <version>3.0.0</version>
</dependency>

Core Imports

import retrofit2.converter.moshi.MoshiConverterFactory;
import com.squareup.moshi.Moshi;
import retrofit2.Retrofit;

Basic Usage

import retrofit2.converter.moshi.MoshiConverterFactory;
import retrofit2.Retrofit;
import com.squareup.moshi.Moshi;

// Basic setup with default Moshi configuration
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(MoshiConverterFactory.create())
    .build();

// Advanced setup with custom Moshi instance
Moshi moshi = new Moshi.Builder()
    .add(new DateAdapter())
    .build();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .build();

// Configuration options
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(
        MoshiConverterFactory.create(moshi)
            .asLenient()
            .failOnUnknown()
            .withNullSerialization()
            .withStreaming()
    )
    .build();

Architecture

The Moshi converter integrates with Retrofit's converter factory system:

  • Factory Pattern: MoshiConverterFactory creates appropriate converters for each request/response type
  • Type Safety: Uses Moshi's JsonAdapter<T> system for compile-time type checking
  • Annotation Support: Automatically handles Moshi's @JsonQualifier annotations
  • Configuration Chain: Immutable builder pattern for customizing JSON processing behavior
  • Streaming Support: Optional streaming serialization for large request bodies

Capabilities

Factory Creation

Creates MoshiConverterFactory instances with default or custom Moshi configurations.

/**
 * Create an instance using a default Moshi instance for conversion.
 */
public static MoshiConverterFactory create();

/**
 * Create an instance using the provided Moshi instance for conversion.
 * @param moshi The Moshi instance to use for JSON processing
 * @throws NullPointerException if moshi is null
 */
public static MoshiConverterFactory create(Moshi moshi);

Configuration Methods

Customize JSON processing behavior through method chaining. Each method returns a new factory instance.

/**
 * Return a new factory which uses lenient adapters that are tolerant of malformed JSON.
 */
public MoshiConverterFactory asLenient();

/**
 * Return a new factory which uses adapters that fail when encountering unknown JSON properties.
 */
public MoshiConverterFactory failOnUnknown();

/**
 * Return a new factory which includes null values in the serialized JSON output.
 */
public MoshiConverterFactory withNullSerialization();

/**
 * Return a new factory which streams serialization of request messages to bytes on the HTTP thread.
 * This is either the calling thread for Call.execute(), or one of OkHttp's background threads 
 * for Call.enqueue(). Response bytes are always converted on OkHttp's background threads.
 */
public MoshiConverterFactory withStreaming();

Converter Creation

Internal methods that Retrofit calls to create converters for specific types. You typically don't call these directly.

/**
 * Creates a converter for response bodies of the specified type.
 * @param type The type to convert to
 * @param annotations Annotations on the method
 * @param retrofit The Retrofit instance
 * @return A converter for ResponseBody to the specified type, or null if not handled
 */
public Converter<ResponseBody, ?> responseBodyConverter(
    Type type, 
    Annotation[] annotations, 
    Retrofit retrofit
);

/**
 * Creates a converter for request bodies of the specified type.
 * @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 A converter from the specified type to RequestBody, or null if not handled
 */
public Converter<?, RequestBody> requestBodyConverter(
    Type type,
    Annotation[] parameterAnnotations,
    Annotation[] methodAnnotations,
    Retrofit retrofit
);

Types

/**
 * The main converter factory class that extends Retrofit's Converter.Factory.
 * Instances are immutable and thread-safe.
 */
public final class MoshiConverterFactory extends Converter.Factory {
    // Factory methods and configuration methods as documented above
}

Error Handling

The converter can throw the following exceptions:

  • JsonDataException: Thrown by Moshi when JSON is malformed or when failOnUnknown() is enabled and unknown properties are encountered
  • IOException: Thrown during I/O operations when reading response bodies or writing request bodies
  • NullPointerException: Thrown when a null Moshi instance is passed to create(Moshi)
// Example error handling
try {
    MyObject obj = apiService.getData().execute().body();
} catch (JsonDataException e) {
    // Handle malformed JSON or unknown properties
    System.err.println("JSON parsing error: " + e.getMessage());
} catch (IOException e) {
    // Handle network or I/O errors
    System.err.println("Network error: " + e.getMessage());
}

Integration Notes

Retrofit Configuration

  • Converter Order: Add MoshiConverterFactory last in the converter chain as it handles all types by default
  • JsonQualifier Support: Method and parameter annotations marked with @JsonQualifier are automatically used for adapter selection
  • Type Erasure: Generic type information is preserved through Retrofit's Type parameter system

Moshi Integration

  • Custom Adapters: Configure custom JsonAdapter instances through the Moshi.Builder
  • Reflection: Works with Moshi's reflection-based adapters for POJOs
  • Code Generation: Compatible with Moshi's code generation for optimal performance

Performance Considerations

  • Streaming: Use withStreaming() for large request bodies to reduce memory usage
  • Thread Safety: All factory instances are immutable and thread-safe
  • Adapter Caching: Moshi adapters are cached internally for reuse across requests

Requirements

  • Java: Requires Java 8+ or Android API 21+
  • Dependencies: Requires retrofit2 and com.squareup.moshi:moshi
  • Optional: com.google.code.findbugs:jsr305 for additional annotations (compile-only)
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/com.squareup.retrofit2/converter-moshi@3.0.x
Publish Source
CLI
Badge
tessl/maven-com-squareup-retrofit2--converter-moshi badge