or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

channel-support.mdcore-messaging.mdhandler-annotations.mdindex.mdmessage-converters.mdmessaging-templates.mdrsocket.mdsimp-configuration.mdstomp-websocket.md
tile.json

message-converters.mddocs/

Message Converters

Comprehensive message payload conversion system supporting JSON (Jackson, Gson, JSON-B, Kotlin Serialization), XML, Protobuf, String, ByteArray, and custom formats with content-type-based automatic converter selection.

Capabilities

MessageConverter Interface

Base strategy interface for converting message payloads between serialized and typed forms.

/**
 * A converter to turn the payload of a Message from serialized form to a typed
 * Object and vice versa.
 */
@FunctionalInterface
public interface MessageConverter {
    /**
     * Convert the payload of a Message from a serialized form to a typed Object
     * of the specified target class.
     * @param message the input message
     * @param targetClass the target class for the conversion
     * @return the result of the conversion, or null if the converter cannot
     *         perform the conversion
     */
    @Nullable
    Object fromMessage(Message<?> message, Class<?> targetClass);

    /**
     * Create a Message whose payload is the result of converting the given
     * payload Object to serialized form.
     * @param payload the Object to convert
     * @param headers optional headers for the message (may be null)
     * @return the new message, or null if the converter does not support the
     *         Object type
     */
    @Nullable
    Message<?> toMessage(Object payload, @Nullable MessageHeaders headers);
}

SmartMessageConverter Interface

Extended converter interface with conversion hint support for additional context.

/**
 * An extended MessageConverter SPI with conversion hint support.
 */
public interface SmartMessageConverter extends MessageConverter {
    /**
     * A variant of fromMessage with an extra conversion context.
     * @param message the input message
     * @param targetClass the target class for the conversion
     * @param conversionHint an extra object passed to the converter, e.g. the
     *        associated MethodParameter (may be null)
     * @return the result of the conversion, or null if the converter cannot
     *         perform the conversion
     */
    @Nullable
    Object fromMessage(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint);

    /**
     * A variant of toMessage with an extra conversion context.
     * @param payload the Object to convert
     * @param headers optional headers for the message (may be null)
     * @param conversionHint an extra object passed to the converter, e.g. the
     *        associated MethodParameter (may be null)
     * @return the new message, or null if the converter does not support the
     *         Object type
     */
    @Nullable
    Message<?> toMessage(Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint);
}

AbstractMessageConverter Class

Abstract base class for MessageConverter implementations with MIME type support and content type resolution.

/**
 * Abstract base class for SmartMessageConverter implementations including
 * support for MIME type handling and invoking a fallback converter when
 * necessary.
 */
public abstract class AbstractMessageConverter implements SmartMessageConverter {
    /**
     * Construct an AbstractMessageConverter supporting one or more MIME types.
     * @param supportedMimeTypes the supported MIME types
     */
    protected AbstractMessageConverter(MimeType... supportedMimeTypes);

    /**
     * Construct an AbstractMessageConverter with one MIME type.
     * @param supportedMimeType the supported MIME type
     */
    protected AbstractMessageConverter(Collection<MimeType> supportedMimeTypes);

    /**
     * Return the supported MIME types.
     */
    public List<MimeType> getSupportedMimeTypes();

    /**
     * Configure the ContentTypeResolver to use to resolve the content type
     * of an input message.
     */
    public void setContentTypeResolver(@Nullable ContentTypeResolver resolver);

    /**
     * Return the configured ContentTypeResolver.
     */
    @Nullable
    public ContentTypeResolver getContentTypeResolver();

    /**
     * Whether strict content type match is required.
     * When enabled, the content type of the message must match exactly
     * the MIME types supported by the converter.
     * Default is false.
     */
    public void setStrictContentTypeMatch(boolean strictContentTypeMatch);

    /**
     * Whether strict content type match is required.
     */
    public boolean isStrictContentTypeMatch();

    /**
     * Configure the preferred serialization class to use (byte[] or String)
     * when converting an Object payload to a Message.
     * Default is byte[].class.
     */
    public void setSerializedPayloadClass(Class<?> payloadClass);

    /**
     * Return the configured preferred serialization payload class.
     */
    public Class<?> getSerializedPayloadClass();

    @Override
    @Nullable
    public Object fromMessage(Message<?> message, Class<?> targetClass);

    @Override
    @Nullable
    public Object fromMessage(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint);

    @Override
    @Nullable
    public Message<?> toMessage(Object payload, @Nullable MessageHeaders headers);

    @Override
    @Nullable
    public Message<?> toMessage(Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint);

    /**
     * Convert the payload of a message from serialized form to an Object.
     * Subclasses must implement this method.
     */
    protected abstract Object convertFromInternal(Message<?> message, Class<?> targetClass,
                                                   @Nullable Object conversionHint);

    /**
     * Convert the payload object to serialized form.
     * Subclasses must implement this method.
     */
    @Nullable
    protected abstract Object convertToInternal(Object payload, @Nullable MessageHeaders headers,
                                                 @Nullable Object conversionHint);

    /**
     * Whether the given class is supported by this converter.
     */
    protected abstract boolean supports(Class<?> clazz);
}

MappingJackson2MessageConverter Class

Jackson 2.x based converter for JSON message payloads.

DEPRECATED since 7.0, scheduled for removal. Use JacksonJsonMessageConverter for Jackson 3.x support.

/**
 * A Jackson 2 based MessageConverter implementation.
 * Compatible with Jackson 2.9 and higher.
 * @deprecated since 7.0, for removal; use JacksonJsonMessageConverter for Jackson 3.x
 */
@Deprecated(since = "7.0", forRemoval = true)
public class MappingJackson2MessageConverter extends AbstractMessageConverter {
    /**
     * Construct a MappingJackson2MessageConverter supporting the
     * application/json MIME type with UTF-8 character set.
     */
    public MappingJackson2MessageConverter();

    /**
     * Construct a MappingJackson2MessageConverter supporting one or more
     * custom MIME types.
     */
    public MappingJackson2MessageConverter(MimeType... supportedMimeTypes);

    /**
     * Construct a MappingJackson2MessageConverter with a pre-configured ObjectMapper.
     * @param objectMapper the ObjectMapper to use
     * @since 6.1
     */
    public MappingJackson2MessageConverter(ObjectMapper objectMapper);

    /**
     * Construct a MappingJackson2MessageConverter with a pre-configured ObjectMapper
     * and custom MIME types.
     * @param objectMapper the ObjectMapper to use
     * @param supportedMimeTypes the supported MIME types
     * @since 6.1
     */
    public MappingJackson2MessageConverter(ObjectMapper objectMapper, MimeType... supportedMimeTypes);

    /**
     * Set the ObjectMapper for this converter.
     * If not set, a default ObjectMapper will be created and used.
     */
    public void setObjectMapper(ObjectMapper objectMapper);

    /**
     * Return the underlying ObjectMapper for this converter.
     */
    public ObjectMapper getObjectMapper();

    /**
     * Whether to use the Jackson pretty-print feature.
     * Default is false.
     */
    public void setPrettyPrint(boolean prettyPrint);
}

Usage Examples:

import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.util.MimeTypeUtils;

// Basic usage with defaults
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();

// Convert object to message
User user = new User("john", "john@example.com");
Message<?> message = converter.toMessage(user, null);

// Convert message to object
User receivedUser = (User) converter.fromMessage(message, User.class);

// Configure custom ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

converter.setObjectMapper(objectMapper);

// Enable pretty-print
converter.setPrettyPrint(true);

// Support additional MIME types
MappingJackson2MessageConverter customConverter =
    new MappingJackson2MessageConverter(
        MimeTypeUtils.APPLICATION_JSON,
        new MimeType("application", "x-custom-json")
    );

class User {
    private String name;
    private String email;

    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }

    // Getters and setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

JacksonJsonMessageConverter Class

Jackson 3.x based converter for JSON message payloads (recommended for projects using Jackson 3.x).

/**
 * A Jackson 3.x based MessageConverter implementation.
 * Compatible with Jackson 3.x (tools.jackson.databind).
 * @since 7.0
 */
public class JacksonJsonMessageConverter extends AbstractMessageConverter {
    /**
     * Construct a JacksonJsonMessageConverter with a JsonMapper customized
     * with the JacksonModules found by MapperBuilder.findModules().
     */
    public JacksonJsonMessageConverter();

    /**
     * Construct a JacksonJsonMessageConverter with a JsonMapper customized
     * with the JacksonModules and the provided MIME types.
     */
    public JacksonJsonMessageConverter(MimeType... supportedMimeTypes);

    /**
     * Construct a JacksonJsonMessageConverter with the provided JsonMapper.
     */
    public JacksonJsonMessageConverter(JsonMapper mapper);

    /**
     * Construct a JacksonJsonMessageConverter with the provided JsonMapper.Builder
     * customized with JacksonModules found by MapperBuilder.findModules().
     */
    public JacksonJsonMessageConverter(JsonMapper.Builder builder);

    /**
     * Construct with the provided JsonMapper and supported MIME types.
     */
    public JacksonJsonMessageConverter(JsonMapper mapper, MimeType... supportedMimeTypes);

    /**
     * Construct with the provided JsonMapper.Builder customized with JacksonModules,
     * and the provided MIME types.
     */
    public JacksonJsonMessageConverter(JsonMapper.Builder builder, MimeType... supportedMimeTypes);

    /**
     * Return the underlying JsonMapper for this converter.
     */
    protected JsonMapper getJsonMapper();
}

Usage Examples:

import org.springframework.messaging.converter.JacksonJsonMessageConverter;
import org.springframework.messaging.Message;
import tools.jackson.databind.json.JsonMapper;
import tools.jackson.databind.SerializationFeature;

// Basic usage with defaults (Jackson 3.x)
JacksonJsonMessageConverter converter = new JacksonJsonMessageConverter();

// Convert object to message
User user = new User("john", "john@example.com");
Message<?> message = converter.toMessage(user, null);

// Convert message to object
User receivedUser = (User) converter.fromMessage(message, User.class);

// Configure custom JsonMapper (Jackson 3.x API)
JsonMapper jsonMapper = JsonMapper.builder()
    .enable(SerializationFeature.INDENT_OUTPUT)
    .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
    .build();

converter = new JacksonJsonMessageConverter(jsonMapper);

// Use JsonMapper.Builder with auto-discovery of modules
JacksonJsonMessageConverter customConverter =
    new JacksonJsonMessageConverter(JsonMapper.builder());

// Support additional MIME types
JacksonJsonMessageConverter mimeConverter =
    new JacksonJsonMessageConverter(
        new MimeType("application", "json"),
        new MimeType("application", "x-custom-json")
    );

class User {
    private String name;
    private String email;

    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }

    // Getters and setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

CompositeMessageConverter Class

Delegates conversion to a list of converters, trying each until one succeeds.

/**
 * A MessageConverter that delegates to a list of registered converters
 * to be invoked until one of them returns a non-null result.
 */
public class CompositeMessageConverter implements SmartMessageConverter {
    /**
     * Create an instance with the given converters, invoking each in the
     * order they are provided.
     */
    public CompositeMessageConverter(Collection<MessageConverter> converters);

    /**
     * Return the underlying list of converters.
     */
    public List<MessageConverter> getConverters();

    @Override
    @Nullable
    public Object fromMessage(Message<?> message, Class<?> targetClass);

    @Override
    @Nullable
    public Object fromMessage(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint);

    @Override
    @Nullable
    public Message<?> toMessage(Object payload, @Nullable MessageHeaders headers);

    @Override
    @Nullable
    public Message<?> toMessage(Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint);

    @Override
    public String toString();
}

Usage Examples:

import org.springframework.messaging.converter.*;
import java.util.Arrays;
import java.util.List;

// Create composite converter with multiple converters
List<MessageConverter> converters = Arrays.asList(
    new MappingJackson2MessageConverter(),
    new StringMessageConverter(),
    new ByteArrayMessageConverter()
);

CompositeMessageConverter compositeConverter = new CompositeMessageConverter(converters);

// The composite will try each converter in order
// JSON objects -> MappingJackson2MessageConverter
// Strings -> StringMessageConverter
// byte arrays -> ByteArrayMessageConverter

// Use with template
GenericMessagingTemplate template = new GenericMessagingTemplate(channel);
template.setMessageConverter(compositeConverter);

// Send different types - appropriate converter will be selected
template.convertAndSend("/topic/data", new User("alice", "alice@example.com")); // JSON
template.convertAndSend("/topic/text", "Hello World"); // String
template.convertAndSend("/topic/binary", new byte[]{1, 2, 3}); // Binary

GsonMessageConverter Class

Google Gson based converter for JSON message payloads.

/**
 * Implementation of MessageConverter that can read and write JSON
 * using Google's Gson library.
 */
public class GsonMessageConverter extends AbstractJsonMessageConverter {
    /**
     * Construct a GsonMessageConverter with default configuration.
     */
    public GsonMessageConverter();

    /**
     * Set the Gson instance to use.
     * If not set, a default Gson instance is used.
     */
    public void setGson(Gson gson);

    /**
     * Return the configured Gson instance.
     */
    public Gson getGson();
}

JsonbMessageConverter Class

JSON-B (Jakarta JSON Binding) based converter for JSON message payloads.

/**
 * Implementation of MessageConverter that can read and write JSON
 * using the JSON Binding API (JSON-B).
 */
public class JsonbMessageConverter extends AbstractJsonMessageConverter {
    /**
     * Construct a JsonbMessageConverter with default configuration.
     */
    public JsonbMessageConverter();

    /**
     * Set the Jsonb instance to use.
     * If not set, a default Jsonb instance is created.
     */
    public void setJsonb(Jsonb jsonb);

    /**
     * Return the configured Jsonb instance.
     */
    public Jsonb getJsonb();
}

KotlinSerializationJsonMessageConverter Class

Kotlin Serialization based converter for JSON message payloads.

/**
 * Implementation of MessageConverter that can read and write JSON
 * using Kotlin serialization.
 * Requires kotlinx-serialization-json to be on the classpath.
 */
public class KotlinSerializationJsonMessageConverter extends AbstractJsonMessageConverter {
    /**
     * Construct a KotlinSerializationJsonMessageConverter with default configuration.
     */
    public KotlinSerializationJsonMessageConverter();

    /**
     * Construct with a custom Json format.
     */
    public KotlinSerializationJsonMessageConverter(Json json);
}

StringMessageConverter Class

Converter for String payloads with text/plain MIME type support.

/**
 * A MessageConverter that supports MIME type "text/plain" with the
 * payload converted to and from a String.
 */
public class StringMessageConverter extends AbstractMessageConverter {
    /**
     * Construct a StringMessageConverter supporting the "text/plain" MIME type
     * with UTF-8 character set.
     */
    public StringMessageConverter();

    /**
     * Construct a StringMessageConverter supporting the "text/plain" MIME type
     * with a specific character set.
     */
    public StringMessageConverter(Charset defaultCharset);
}

Usage Examples:

import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import java.nio.charset.StandardCharsets;

// Default UTF-8 charset
StringMessageConverter converter = new StringMessageConverter();

// Convert string to message
Message<?> message = converter.toMessage("Hello World", null);

// Convert message to string
String text = (String) converter.fromMessage(message, String.class);

// Custom charset
StringMessageConverter utf16Converter =
    new StringMessageConverter(StandardCharsets.UTF_16);

ByteArrayMessageConverter Class

Converter for byte array payloads with application/octet-stream MIME type support.

/**
 * A MessageConverter that supports MIME type "application/octet-stream" with the
 * payload converted to and from a byte array.
 */
public class ByteArrayMessageConverter extends AbstractMessageConverter {
    /**
     * Construct a ByteArrayMessageConverter supporting the
     * "application/octet-stream" MIME type.
     */
    public ByteArrayMessageConverter();
}

Usage Examples:

import org.springframework.messaging.converter.ByteArrayMessageConverter;
import org.springframework.messaging.Message;

ByteArrayMessageConverter converter = new ByteArrayMessageConverter();

// Convert byte array to message
byte[] data = {1, 2, 3, 4, 5};
Message<?> message = converter.toMessage(data, null);

// Convert message to byte array
byte[] receivedData = (byte[]) converter.fromMessage(message, byte[].class);

ProtobufMessageConverter Class

Converter for Protocol Buffers message payloads supporting multiple formats.

/**
 * An MessageConverter that reads and writes
 * com.google.protobuf.Messages using Google Protocol Buffers.
 */
public class ProtobufMessageConverter extends AbstractMessageConverter {
    /**
     * The default charset used for serializing text-based protobuf formats.
     */
    public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

    /**
     * The MIME type for protobuf messages.
     */
    public static final MimeType PROTOBUF =
        new MimeType("application", "x-protobuf", DEFAULT_CHARSET);

    /**
     * Construct a ProtobufMessageConverter with support for
     * application/x-protobuf, text/plain, application/json, and application/xml.
     */
    public ProtobufMessageConverter();

    /**
     * Construct a ProtobufMessageConverter with support for
     * application/x-protobuf and additional MIME types.
     */
    public ProtobufMessageConverter(ExtensionRegistry extensionRegistry);

    /**
     * Return the MIME types supported for writing.
     */
    public MimeType[] supportedMediaTypes();

    /**
     * Check if the converter supports write-only for the given MIME type.
     */
    public boolean supportsWriteOnly(@Nullable MimeType mimeType);

    /**
     * Merge the given message with additional data from the input message.
     */
    public void merge(org.springframework.messaging.Message<?> message,
                     Charset charset,
                     MimeType contentType,
                     ExtensionRegistry extensionRegistry,
                     com.google.protobuf.Message.Builder builder)
            throws IOException;

    /**
     * Print the protobuf message to the output stream.
     */
    public void print(com.google.protobuf.Message message,
                     OutputStream output,
                     MimeType contentType,
                     Charset charset)
            throws IOException;
}

ProtobufJsonFormatMessageConverter Class

Protobuf converter using the official JSON format from google.protobuf.util.

/**
 * Subclass of ProtobufMessageConverter for use with the official
 * "com.google.protobuf.util.JsonFormat" utility for JSON support.
 */
public class ProtobufJsonFormatMessageConverter extends ProtobufMessageConverter {
    /**
     * Construct a ProtobufJsonFormatMessageConverter with default parsers.
     */
    public ProtobufJsonFormatMessageConverter();

    /**
     * Construct with custom JSON parser and printer.
     */
    public ProtobufJsonFormatMessageConverter(JsonFormat.Parser parser, JsonFormat.Printer printer);

    /**
     * Construct with custom JSON parser, printer, and extension registry.
     */
    public ProtobufJsonFormatMessageConverter(JsonFormat.Parser parser,
                                              JsonFormat.Printer printer,
                                              ExtensionRegistry extensionRegistry);
}

MarshallingMessageConverter Class

Converter for XML payloads using Spring's OXM (Object/XML Mapping) abstraction.

/**
 * Implementation of MessageConverter that can read and write XML using Spring's
 * Marshaller and Unmarshaller abstractions.
 */
public class MarshallingMessageConverter extends AbstractMessageConverter {
    /**
     * Construct a MarshallingMessageConverter with no Marshaller or Unmarshaller set.
     * The Marshaller and Unmarshaller must be set after construction.
     */
    public MarshallingMessageConverter();

    /**
     * Construct a MarshallingMessageConverter with the given Marshaller set.
     * If the Marshaller also implements Unmarshaller, it is used for both.
     */
    public MarshallingMessageConverter(Marshaller marshaller);

    /**
     * Construct a MarshallingMessageConverter with the given Marshaller and Unmarshaller.
     */
    public MarshallingMessageConverter(Marshaller marshaller, Unmarshaller unmarshaller);

    /**
     * Set the Marshaller to be used by this message converter.
     */
    public void setMarshaller(@Nullable Marshaller marshaller);

    /**
     * Return the configured Marshaller.
     */
    @Nullable
    public Marshaller getMarshaller();

    /**
     * Set the Unmarshaller to be used by this message converter.
     */
    public void setUnmarshaller(@Nullable Unmarshaller unmarshaller);

    /**
     * Return the configured Unmarshaller.
     */
    @Nullable
    public Unmarshaller getUnmarshaller();
}

Usage Examples:

import org.springframework.messaging.converter.MarshallingMessageConverter;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;

// Configure JAXB marshaller
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(User.class, Order.class);

// Create converter
MarshallingMessageConverter converter = new MarshallingMessageConverter(marshaller);

// Convert object to XML message
User user = new User("john", "john@example.com");
Message<?> message = converter.toMessage(user, null);

// Convert XML message to object
User receivedUser = (User) converter.fromMessage(message, User.class);

SimpleMessageConverter Class

Basic converter that unwraps or wraps message payloads with minimal conversion.

/**
 * A simple converter that simply unwraps the message payload as long as it matches the
 * expected target class. Or, for the reverse direction, simply wraps the payload in a message.
 */
public class SimpleMessageConverter implements MessageConverter {
    @Override
    @Nullable
    public Object fromMessage(Message<?> message, Class<?> targetClass);

    @Override
    public Message<?> toMessage(Object payload, @Nullable MessageHeaders headers);
}

GenericMessageConverter Class

Extension of SimpleMessageConverter using Spring's ConversionService for type conversion.

/**
 * An extension of the SimpleMessageConverter that uses a
 * ConversionService to convert the payload to the expected type.
 */
public class GenericMessageConverter extends SimpleMessageConverter {
    /**
     * Create a GenericMessageConverter with a default ConversionService.
     */
    public GenericMessageConverter();

    /**
     * Create a GenericMessageConverter with the given ConversionService.
     */
    public GenericMessageConverter(ConversionService conversionService);

    @Override
    @Nullable
    public Object fromMessage(Message<?> message, Class<?> targetClass);
}

ContentTypeResolver Interface

Strategy for resolving the content type of a message.

/**
 * Strategy to resolve the content type of a message.
 */
@FunctionalInterface
public interface ContentTypeResolver {
    /**
     * Determine the MimeType of a message from the given MessageHeaders.
     * @param headers the headers to use for the resolution
     * @return the resolved MimeType, or null if none found
     */
    @Nullable
    MimeType resolve(@Nullable MessageHeaders headers);
}

DefaultContentTypeResolver Class

Default content type resolver checking the MessageHeaders.CONTENT_TYPE header.

/**
 * A default ContentTypeResolver that checks the
 * MessageHeaders.CONTENT_TYPE header or falls back to a default value.
 */
public class DefaultContentTypeResolver implements ContentTypeResolver {
    /**
     * Set the default MIME type to use when the message headers do not
     * contain a content type header.
     */
    public void setDefaultMimeType(@Nullable MimeType defaultMimeType);

    /**
     * Return the default content type.
     */
    @Nullable
    public MimeType getDefaultMimeType();

    @Override
    @Nullable
    public MimeType resolve(@Nullable MessageHeaders headers);

    @Override
    public String toString();
}

Usage Examples:

import org.springframework.messaging.converter.DefaultContentTypeResolver;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.util.MimeTypeUtils;

// Configure content type resolver
DefaultContentTypeResolver resolver = new DefaultContentTypeResolver();
resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON);

// Use with converter
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setContentTypeResolver(resolver);

// Enable strict content type matching
converter.setStrictContentTypeMatch(true);

MessageConversionException

Exception thrown when message conversion fails.

/**
 * An exception raised by MessageConverter implementations when a conversion fails.
 */
public class MessageConversionException extends MessagingException {
    /**
     * Create a new MessageConversionException.
     * @param description the detail message
     */
    public MessageConversionException(String description);

    /**
     * Create a new MessageConversionException.
     * @param description the detail message
     * @param cause the root cause
     */
    public MessageConversionException(String description, Throwable cause);

    /**
     * Create a new MessageConversionException.
     * @param failedMessage the message that could not be converted
     * @param description the detail message
     */
    public MessageConversionException(Message<?> failedMessage, String description);

    /**
     * Create a new MessageConversionException.
     * @param failedMessage the message that could not be converted
     * @param description the detail message
     * @param cause the root cause
     */
    public MessageConversionException(Message<?> failedMessage, String description, Throwable cause);
}

Usage Examples:

import org.springframework.messaging.converter.*;
import org.springframework.messaging.Message;

try {
    MessageConverter converter = new MappingJackson2MessageConverter();

    // Attempt conversion
    Object result = converter.fromMessage(message, MyComplexType.class);

    if (result == null) {
        throw new MessageConversionException(message,
            "Could not convert message to " + MyComplexType.class.getName());
    }
} catch (MessageConversionException e) {
    System.err.println("Conversion failed: " + e.getMessage());
    Message<?> failedMessage = e.getFailedMessage();
    // Handle conversion failure
}

class MyComplexType {
    // Type definition
}

Complete Converter Setup Example

import org.springframework.messaging.converter.*;
import org.springframework.messaging.core.GenericMessagingTemplate;
import org.springframework.messaging.support.ExecutorSubscribableChannel;
import org.springframework.util.MimeTypeUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Arrays;

// Create multiple converters
MappingJackson2MessageConverter jsonConverter = new MappingJackson2MessageConverter();
jsonConverter.setPrettyPrint(true);

StringMessageConverter stringConverter = new StringMessageConverter();
ByteArrayMessageConverter byteConverter = new ByteArrayMessageConverter();

ProtobufMessageConverter protobufConverter = new ProtobufMessageConverter();

// Combine into composite
CompositeMessageConverter compositeConverter = new CompositeMessageConverter(
    Arrays.asList(
        jsonConverter,
        stringConverter,
        byteConverter,
        protobufConverter
    )
);

// Configure template with converter
ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel();
GenericMessagingTemplate template = new GenericMessagingTemplate(channel);
template.setMessageConverter(compositeConverter);

// Now template can handle multiple payload types
template.convertAndSend("/topic/json", new User("alice", "alice@example.com"));
template.convertAndSend("/topic/text", "Hello World");
template.convertAndSend("/topic/binary", new byte[]{1, 2, 3});