CtrlK
BlogDocsLog inGet started
Tessl Logo

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

A Retrofit Converter which uses Gson for serialization to and from JSON

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

Retrofit2 Gson Converter

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.

Package Information

  • Package Name: converter-gson

  • Group ID: com.squareup.retrofit2

  • Package Type: Maven

  • Language: Java

  • Installation:

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

    Gradle:

    implementation 'com.squareup.retrofit2:converter-gson:3.0.0'

Core Imports

import retrofit2.converter.gson.GsonConverterFactory;
import com.google.gson.Gson;
import retrofit2.Retrofit;

Basic Usage

import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.Retrofit;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.FieldNamingPolicy;

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

// Usage with custom Gson instance
Gson customGson = new GsonBuilder()
    .setDateFormat("yyyy-MM-dd HH:mm:ss")
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .create();

Retrofit retrofitWithCustomGson = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create(customGson))
    .build();

// Enable streaming for large request bodies
Retrofit streamingRetrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create().withStreaming())
    .build();

Architecture

The Gson converter consists of the main factory class and internal converter implementations:

  • GsonConverterFactory: Main factory class that creates request and response body converters
  • GsonRequestBodyConverter: Package-private converter that handles Java object to JSON request body conversion
  • GsonResponseBodyConverter: Package-private converter that handles JSON response body to Java object conversion
  • GsonStreamingRequestBody: Streaming request body implementation that writes JSON directly to HTTP thread without buffering
  • Streaming Support: Optional streaming mode that prevents memory buffering by writing JSON directly during HTTP transmission
  • UTF-8 Encoding: Consistent UTF-8 encoding for all JSON operations

Capabilities

Converter Factory Creation

Creates converter factory instances with various configuration options.

/**
 * A converter factory which uses Gson for JSON serialization/deserialization.
 * This factory should be added last to allow other converters to handle their types first.
 */
public final class GsonConverterFactory extends Converter.Factory {
    
    /**
     * Create an instance using a default Gson instance for conversion.
     * Encoding to JSON and decoding from JSON (when no charset is specified by a header) will use UTF-8.
     * 
     * @return GsonConverterFactory instance with default Gson configuration
     */
    public static GsonConverterFactory create();
    
    /**
     * Create an instance using the provided Gson instance for conversion.
     * Encoding to JSON and decoding from JSON (when no charset is specified by a header) will use UTF-8.
     * 
     * @param gson The Gson instance to use for conversion (must not be null)
     * @return GsonConverterFactory instance with custom Gson configuration
     * @throws NullPointerException if gson is null
     */
    public static GsonConverterFactory create(Gson gson);
    
    /**
     * 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 to message instances on one of OkHttp's background threads.
     * 
     * Streaming prevents buffering of the entire JSON in memory by writing directly to the HTTP stream.
     * 
     * @return GsonConverterFactory instance with streaming enabled
     */
    public GsonConverterFactory withStreaming();
}

Usage Examples:

// Default factory with built-in Gson configuration
GsonConverterFactory factory = GsonConverterFactory.create();

// Custom factory with specific Gson settings
Gson gson = new GsonBuilder()
    .setDateFormat("yyyy-MM-dd")
    .excludeFieldsWithoutExposeAnnotation()
    .create();
GsonConverterFactory customFactory = GsonConverterFactory.create(gson);

// Enable streaming for large request bodies
GsonConverterFactory streamingFactory = GsonConverterFactory.create()
    .withStreaming();

// Combine custom Gson with streaming
GsonConverterFactory advancedFactory = GsonConverterFactory.create(customGson)
    .withStreaming();

Response Body Conversion

Automatically converts HTTP response bodies from JSON to Java objects using Gson's type system.

/**
 * Creates a converter for ResponseBody to specified type.
 * Called automatically by Retrofit when processing API responses.
 * 
 * @param type The target type for conversion
 * @param annotations Method annotations
 * @param retrofit The Retrofit instance
 * @return Converter instance or null if this factory cannot handle the type
 */
public Converter<ResponseBody, ?> responseBodyConverter(
    Type type, 
    Annotation[] annotations, 
    Retrofit retrofit
);

Request Body Conversion

Automatically converts Java objects to JSON request bodies using Gson serialization.

/**
 * Creates a converter for specified type to RequestBody.
 * Called automatically by Retrofit when processing API requests.
 * 
 * @param type The source type for conversion
 * @param parameterAnnotations Parameter annotations
 * @param methodAnnotations Method annotations  
 * @param retrofit The Retrofit instance
 * @return Converter instance or null if this factory cannot handle the type
 */
public Converter<?, RequestBody> requestBodyConverter(
    Type type,
    Annotation[] parameterAnnotations,
    Annotation[] methodAnnotations,
    Retrofit retrofit
);

Types

// Standard Retrofit and Gson types used by the converter
import retrofit2.Converter;
import retrofit2.Retrofit;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.JsonIOException;
import com.google.gson.reflect.TypeToken;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.MediaType;
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;
import java.io.IOException;

Error Handling

The converter handles several error conditions:

  • NullPointerException: Thrown when null Gson instance is passed to create(Gson)
  • JsonIOException: Thrown with message "JSON document was not fully consumed." when response JSON contains extra content after the expected object
  • Gson Serialization Errors: Propagated from underlying Gson serialization/deserialization operations
  • IOException: Propagated from underlying I/O operations during JSON processing

Thread Safety

All components of the Gson converter are thread-safe:

  • GsonConverterFactory: Immutable and can be shared across multiple Retrofit instances
  • Internal Converters: Stateless and thread-safe for concurrent request processing
  • Gson Integration: Leverages Gson's thread-safe TypeAdapter system

Best Practices

  1. Factory Placement: Add GsonConverterFactory last in the converter list to allow other converters to handle their specific types first
  2. Custom Gson Configuration: Use custom Gson instances for specific serialization requirements (date formats, field naming, etc.)
  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
  4. Error Handling: Handle JsonIOException and other Gson-related exceptions appropriately in your application
  5. UTF-8 Encoding: The converter always uses UTF-8 encoding, which is the standard for JSON data
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/com.squareup.retrofit2/converter-gson@3.0.x
Publish Source
CLI
Badge
tessl/maven-com-squareup-retrofit2--converter-gson badge