Http Message Converters with the Spring Framework

1. Overview

This article describes how to Configure HttpMessageConverters in Spring.

Simply put, we can use message converters to marshall and unmarshall Java Objects to and from JSON, XML, etc – over HTTP.

Further reading:

Spring MVC Content Negotiation

A guide to configuring content negotiation in a Spring MVC application and on enabling and disabling the various available strategies.

Read more

Returning Image/Media Data with Spring MVC

The article shows the alternatives for returning image (or other media) with Spring MVC and discusses the pros and cons of each approach.

Read more

Binary Data Formats in a Spring REST API

In this article we explore how to configure Spring REST mechanism to utilize binary data formats which we illustrate with Kryo. Moreover we show how to support multiple data formats with Google Protocol buffers.

Read more

2. The Basics

2.1. Enable Web MVC

To start with, the Web Application needs to be configured with Spring MVC support. A convenient and very customizable way to do this is to use the @EnableWebMvc annotation:

@EnableWebMvc
@Configuration
@ComponentScan({ "com.baeldung.web" })
public class WebConfig implements WebMvcConfigurer {
    ...
}

Note that this class implements WebMvcConfigurer – which will allow us to change the default list of Http Converters with our own.

2.2. The Default Message Converters

By default, the following HttpMessageConverters instances are pre-enabled:

  • ByteArrayHttpMessageConverter – converts byte arrays

  • StringHttpMessageConverter – converts Strings

  • ResourceHttpMessageConverter – converts org.springframework.core.io.Resource for any type of octet stream

  • SourceHttpMessageConverter – converts javax.xml.transform.Source

  • FormHttpMessageConverter – converts form data to/from a MultiValueMap<String, String>.

  • Jaxb2RootElementHttpMessageConverter – converts Java objects to/from XML (added only if JAXB2 is present on the classpath)

  • MappingJackson2HttpMessageConverter – converts JSON (added only if Jackson 2 is present on the classpath)_
    _

  • MappingJacksonHttpMessageConverter – converts JSON (added only if Jackson is present on the classpath)

  • AtomFeedHttpMessageConverter – converts Atom feeds (added only if Rome is present on the classpath)

  • RssChannelHttpMessageConverter – converts RSS feeds (added only if Rome is present on the classpath)

3. Client-Server Communication – JSON Only


==== 3.1. High-Level Content Negotiation

Each HttpMessageConverter implementation has one or several associated MIME Types.

When receiving a new request, Spring will use the “Accept” header to determine the media type that it needs to respond with.

It will then try to find a registered converter that’s capable of handling that specific media type. Finally, it will use this to convert the entity and send back the response.

The process is similar for receiving a request which contains JSON information. The framework will use the “*Content-Type” header to determine the media type of the request body*.

It will then search for a HttpMessageConverter that can convert the body sent by the client to a Java Object.

Let’s clarify this with a quick example:

  • the Client sends a GET request to /foos with the Accept header set to application/json – to get all Foo resources as JSON

  • the Foo Spring Controller is hit and returns the corresponding Foo Java entities

  • Spring then uses one of the Jackson message converters to marshall the entities to JSON

Let’s now look at the specifics of how this works – and how we can leverage the @ResponseBody and @RequestBody annotations.

3.2. @ResponseBody

@ResponseBody on a Controller method indicates to Spring that the return value of the method is serialized directly to the body of the HTTP Response. As discussed above, the “Accept” header specified by the Client will be used to choose the appropriate Http Converter to marshall the entity.

Let’s look at a simple example:

@GetMapping("/{id}")
public @ResponseBody Foo findById(@PathVariable long id) {
    return fooService.findById(id);
}

Now, the client will specify the “Accept” header to application/json in the request – example curl command:

curl --header "Accept: application/json"
  http://localhost:8080/spring-boot-rest/foos/1

The Foo class:

public class Foo {
    private long id;
    private String name;
}

And the Http Response Body:

{
    "id": 1,
    "name": "Paul",
}

3.3. @RequestBody

We can use the @RequestBody annotation on the argument of a Controller method to indicate that the body of the HTTP Request is deserialized to that particular Java entity. To determine the appropriate converter, Spring will use the “Content-Type” header from the client request.

Let’s look at an example:

@PutMapping("/{id}")
public @ResponseBody void update(@RequestBody Foo foo, @PathVariable String id) {
    fooService.update(foo);
}

Next, let’s consume this with a JSON object – we’re specifying “Content-Type to be application/json:

curl -i -X PUT -H "Content-Type: application/json"
-d '{"id":"83","name":"klik"}' http://localhost:8080/spring-boot-rest/foos/1

We get back a 200 OK – a successful response:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Length: 0
Date: Fri, 10 Jan 2014 11:18:54 GMT

4. Custom Converters Configuration

We can also customize the message converters by implementing the WebMvcConfigurer interface and overriding the configureMessageConverters method:

@EnableWebMvc
@Configuration
@ComponentScan({ "com.baeldung.web" })
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(
      List<HttpMessageConverter<?>> converters) {

        messageConverters.add(createXmlHttpMessageConverter());
        messageConverters.add(new MappingJackson2HttpMessageConverter());
    }
    private HttpMessageConverter<Object> createXmlHttpMessageConverter() {
        MarshallingHttpMessageConverter xmlConverter =
          new MarshallingHttpMessageConverter();

        XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
        xmlConverter.setMarshaller(xstreamMarshaller);
        xmlConverter.setUnmarshaller(xstreamMarshaller);

        return xmlConverter;
    }
}

And here is the corresponding XML configuration:

<context:component-scan base-package="org.baeldung.web" />
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
            <property name="marshaller" ref="xstreamMarshaller" />
            <property name="unmarshaller" ref="xstreamMarshaller" />
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller" />

In this example, we’re creating a new converter – the MarshallingHttpMessageConverter – and using the Spring XStream support to configure it. This allows a great deal of flexibility since we’re working with the low-level APIs of the underlying marshalling framework – in this case XStream – and we can configure that however we want.

Note that this example requires adding the XStream library to the classpath.

Also be aware that by extending this support class, we’re losing the default message converters which were previously pre-registered.

We can of course now do the same for Jackson – by defining our own MappingJackson2HttpMessageConverter. We can now set a custom ObjectMapper on this converter and have it configured as we need to.

In this case, XStream was the selected marshaller/unmarshaller implementation, but others like CastorMarshaller can be used as well.

At this point – with XML enabled on the back end – we can consume the API with XML Representations:

curl --header "Accept: application/xml"
  http://localhost:8080/spring-boot-rest/foos/1

4.1. Spring Boot Support

If we’re using Spring Boot we can avoid implementing the WebMvcConfigurer and adding all the Message Converters manually as we did above.

We can just define different HttpMessageConverter beans in the context, and Spring Boot will add them automatically to the autoconfiguration that it creates:

@Bean
public HttpMessageConverter<Object> createXmlHttpMessageConverter() {
    MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();

    // ...

    return xmlConverter;
}

5. Using Spring’s RestTemplate with Http Message Converters

As well as with the server side, Http Message Conversion can be configured in the client side on the Spring RestTemplate.

We’re going to configure the template with the “Accept” and “Content-Type” headers when appropriate. Then we’ll try to consume the REST API with full marshalling and unmarshalling of the Foo Resource – both with JSON and with XML.

5.1. Retrieving the Resource with No Accept Header

[source,java,gutter:,true]

@Test
public void testGetFoo() {
    String URI = “http://localhost:8080/spring-boot-rest/foos/{id}";
    RestTemplate restTemplate = new RestTemplate();
    Foo foo = restTemplate.getForObject(URI, Foo.class, "1");
    Assert.assertEquals(new Integer(1), foo.getId());
}

5.2. Retrieving a Resource with application/xml Accept Header

[[retrieving-a-resource-with-applicationxml—​accept-header]]Let’s now explicitly retrieve the Resource as an XML Representation. We’re going to define a set of Converters and set these on the RestTemplate.

Because we’re consuming XML, we’re going to use the same XStream marshaller as before:

@Test
public void givenConsumingXml_whenReadingTheFoo_thenCorrect() {
    String URI = BASE_URI + "foos/{id}";
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(getMessageConverters());

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    ResponseEntity<Foo> response =
      restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
    Foo resource = response.getBody();

    assertThat(resource, notNullValue());
}
private List<HttpMessageConverter<?>> getMessageConverters() {
    XStreamMarshaller marshaller = new XStreamMarshaller();
    MarshallingHttpMessageConverter marshallingConverter =
      new MarshallingHttpMessageConverter(marshaller);

    List<HttpMessageConverter<?>> converters =
      ArrayList<HttpMessageConverter<?>>();
    converters.add(marshallingConverter);
    return converters;
}

5.3. Retrieving a Resource with application/json Accept Header

[[retrieving-a-resource-with-applicationjson—​accept-header]]Similarly, let’s now consume the REST API by asking for JSON:

@Test
public void givenConsumingJson_whenReadingTheFoo_thenCorrect() {
    String URI = BASE_URI + "foos/{id}";

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(getMessageConverters());

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    ResponseEntity<Foo> response =
      restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
    Foo resource = response.getBody();

    assertThat(resource, notNullValue());
}
private List<HttpMessageConverter<?>> getMessageConverters() {
    List<HttpMessageConverter<?>> converters =
      new ArrayList<HttpMessageConverter<?>>();
    converters.add(new MappingJackson2HttpMessageConverter());
    return converters;
}

5.4. Update a Resource with XML Content-Type

Finally, let’s also send JSON data to the REST API and specify the media type of that data via the Content-Type header:

@Test
public void givenConsumingXml_whenWritingTheFoo_thenCorrect() {
    String URI = BASE_URI + "foos/{id}";
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(getMessageConverters());

    Foo resource = new Foo(4, "jason");
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType((MediaType.APPLICATION_XML));
    HttpEntity<Foo> entity = new HttpEntity<Foo>(resource, headers);

    ResponseEntity<Foo> response = restTemplate.exchange(
      URI, HttpMethod.PUT, entity, Foo.class, resource.getId());
    Foo fooResponse = response.getBody();

    Assert.assertEquals(resource.getId(), fooResponse.getId());
}

What’s interesting here is that we’re able to mix the media types – we’re sending XML data but we’re waiting for JSON data back from the server. This shows just how powerful the Spring conversion mechanism really is.

6. Conclusion

In this tutorial, we looked at how Spring MVC allows us to specify and fully customize Http Message Converters to automatically marshall/unmarshall Java Entities to and from XML or JSON. This is, of course, a simplistic definition, and there is so much more that the message conversion mechanism can do – as we can see from the last test example.

We have also looked at how to leverage the same powerful mechanism with the RestTemplate client – leading to a fully type-safe way of consuming the API.

As always, the code presented in this article is available over on Github.

Leave a Reply

Your email address will not be published.