001/*
002 * Copyright 2002-2015 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.messaging.converter;
018
019import org.springframework.messaging.Message;
020import org.springframework.messaging.MessageHeaders;
021
022/**
023 * A converter to turn the payload of a {@link Message} from serialized form to a typed
024 * Object and vice versa. The {@link MessageHeaders#CONTENT_TYPE} message header may be
025 * used to specify the media type of the message content.
026 *
027 * @author Mark Fisher
028 * @author Rossen Stoyanchev
029 * @since 4.0
030 */
031public interface MessageConverter {
032
033        /**
034         * Convert the payload of a {@link Message} from a serialized form to a typed Object
035         * of the specified target class. The {@link MessageHeaders#CONTENT_TYPE} header
036         * should indicate the MIME type to convert from.
037         * <p>If the converter does not support the specified media type or cannot perform
038         * the conversion, it should return {@code null}.
039         * @param message the input message
040         * @param targetClass the target class for the conversion
041         * @return the result of the conversion, or {@code null} if the converter cannot
042         * perform the conversion
043         */
044        Object fromMessage(Message<?> message, Class<?> targetClass);
045
046        /**
047         * Create a {@link Message} whose payload is the result of converting the given
048         * payload Object to serialized form. The optional {@link MessageHeaders} parameter
049         * may contain a {@link MessageHeaders#CONTENT_TYPE} header to specify the target
050         * media type for the conversion and it may contain additional headers to be added
051         * to the message.
052         * <p>If the converter does not support the specified media type or cannot perform
053         * the conversion, it should return {@code null}.
054         * @param payload the Object to convert
055         * @param headers optional headers for the message (may be {@code null})
056         * @return the new message, or {@code null} if the converter does not support the
057         * Object type or the target media type
058         */
059        Message<?> toMessage(Object payload, MessageHeaders headers);
060
061}