The Master Class of "Learn Spring Security" is out:

>> CHECK OUT THE COURSE

1. Overview

This article describes how to Configure HttpMessageConverter in Spring.

Simply put, message converters are used 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

The Web Application needs to be configured with Spring MVC support – one convenient and very customizable way to do this is to use the @EnableWebMvc annotation:

@EnableWebMvc
@Configuration
@ComponentScan({ "org.baeldung.web" })
public class WebConfig extends WebMvcConfigurerAdapter {
    ...
}

Note that this class extends WebMvcConfigurerAdapter – 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 of the “Accept” header to determine the media type that it needs to respond with.

It will then try to find a registered converter that is capable of handling that specific media type – and it will use it 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 should 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:

@RequestMapping(method=RequestMethod.GET, value="/foos/{id}")
public @ResponseBody Foo findById(@PathVariable long id) {
    return fooService.get(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-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

@RequestBodyis used on the argument of a Controller method – it indicates to Spring that the body of the HTTP Request is deserialized to that particular Java entity. As discussed previously, the “Content-Type” header specified by the Client will be used to determine the appropriate converter for this.

Let’s look at an example:

@RequestMapping(method=RequestMethod.PUT, value="/foos/{id}")
public @ResponseBody void updateFoo(
  @RequestBody Foo foo, @PathVariable String id) {
    fooService.update(foo);
}

Now, 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-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 customize the message converters by extending the WebMvcConfigurerAdapter class and overriding the configureMessageConverters method:

@EnableWebMvc
@Configuration
@ComponentScan({ "org.baeldung.web" })
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(
      List<HttpMessageConverter<?>> converters) {
    
        messageConverters.add(createXmlHttpMessageConverter());
        messageConverters.add(new MappingJackson2HttpMessageConverter());

        super.configureMessageConverters(converters);
    }
    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:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
  xmlns:mvc="http://www.springframework.org/schema/mvc" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <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" />

</beans>

Note that the XStream library now needs to be present on the classpath.

Also be aware that by extending this support class, we are losing the default message converters which were previously pre-registered – we only have what we define.

Let’s go over this example – we are creating a new converter – the MarshallingHttpMessageConverter – and we’re 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.

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 to – refer to Spring api documentation for full list of available marshallers.

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-rest/foos/1

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 and we’re going to 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

@Test
public void testGetFoo() {
    String URI = “http://localhost:8080/spring-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

Let’s now explicitly retrieve the Resource as an XML Representation – we’re going to define a set of Converters – same way we did previously – and we’re going to 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

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 are 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.

The implementation of this Spring Http Message Converters Tutorial can be downloaded as a working sample project.

This is an Eclipse based project, so it should be easy to import and run as it is.

The Master Class of "Learn Spring Security" is out:

>> CHECK OUT THE COURSE

  • Sheng

    Great article.
    How Can I Git clone this project? Is https://github.com/eugenp/tutorials/tree/master/spring-rest the right url? Thanks.

    • Yes, that is the project covering this article.
      Cheers,
      Eugen.

      • Pranav Sharma

        Hi Eugen , Great article mate!! I would say best on this topic

  • Venkat

    Really nice article with good explanation. I have one use case, could you please help me.

    class Persons implements Serializable{
    private String nameSummary;
    private String addressSummary;
    private String bioSummary;
    }

    Each field in above class contains json data. Below is my Controller class.

    @RequestMapping(value = {“/getSummary”}, method = {RequestMethod.POST}, produces=MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody

    public Persons getSummary(@RequestBody long empId) {

    }

    But in the response i am getting JSON but with escape characters like below:

    {
    “nameSummary”: “{ “_id” : 3242242 , “name” : “juan”}”,
    “addressSummary”: “{ “_id” : 3242243 , “name” : “john”}”,
    “bioSummary”: “{ “_id” : 3242244 , “name” : “eric”}”
    }

    I tried various ways, but not working. Like @JsonRawValue, produces=MediaType.APPLICATION_JSON_VALUE.

    I want the output without escape characters, Could you please do the needful help please.

    Thanks & Regards
    Venkat

    • Venkat

      Hi

      Return Type might not be object,, even List is fine for me.

    • Hey Venkat – first – a github project reproducing the problem in a test would make sense. Second – you can look at the Jackson 2 – JsonFactory – CharacterEscapes to control the way Jackson will escape characters on serialization. Cheers,
      Eugen.

  • Pokuri

    Helpful atricle. I have a question! When we have redirect(or)forward request then response from one first controller marshalled and then redirected or will redirect and handle the marshalling at the end? I want to wrap final response/returnValue from controller into anotehr class bafore handling it to message converter

    • Hey Pokuri – two notes on this. First – doing a redirect/forward is quite the corner case for an API. Second – I would have to take a quick look at a working example (github) – but from the info you’re providing, I’d say that it’s the final controller in the chain that will then return the response body, and it’s on that body that marshalling will occur. Hope that helps. Cheers,
      Eugen.

  • Istiti

    Hi,

    I’m new for all this. Your article helps me. But for the json format I have, I can’ retrieve what I want.

    Here is what I did : curl localhost:9090/players.

    Then the result is :

    {
    “_links” : {
    “search” : {
    “href” : “http://localhost:9090/players/search”
    }
    },
    “_embedded” : {
    “players” : [ {
    “club” : “club1”,
    “gender” : “H”,
    “licence” : “245891”,
    “lastname” : “lastname1”,
    “firstname” : “firstname1”,
    “clssingle” : “C4”,
    “clsdouble” : “C4”,
    “clsmixte” : “C4”,
    “playerStatus” : “ACTIF”,
    “play1” : “SH1”,
    “play2” : “MX1”,
    “_links” : {
    “self” : {
    “href” : “http://localhost:9090/players/10”
    }
    }
    }, {
    “club” : “club1”,
    “gender” : “H”,
    “licence” : “6581414”,
    “lastname” : “lastname2”,
    “firstname” : “firstname2”,
    “clssingle” : “D4”,
    “clsdouble” : “D1”,
    “clsmixte” : “D4”,
    “playerStatus” : “ACTIF”,
    “play1” : “DH”,
    “play2” : “MX2”,
    “_links” : {
    “self” : {
    “href” : “http://localhost:9090/players/11”
    }
    }
    }, {
    ……
    }

    I have tried many advices from internet, but nothing work. Note that I cant get it correctly if I simulate the json format data above. I put them in a file, and with BufferedReader etc, I used String object, it worked.
    Could you please give me an advice ?

    • Hey Istiti – first – it’s not really possible to solve this here in the comments – I would need to look at some actual code. If you have a github repo that I can look at, feel free to contact me on email and I’d be happy to take a look. Cheers,
      Eugen.

  • Bill

    Eugen –

    Again, great informative article. I’m having and issue with overriding configureMessageConverters in my config class; it never seems to get called. If I add an override for requestMappingHandlerAdapter and call its super, then my configureMessageConverters gets called. So, its working, but why won’t the configureMessageConverters get called on its own? I’m using spring 4.0.6.

    Bill

    • Hey Bill – without actually looking at your code, I would say that – a config class (that extends WebMvcConfigurerAdapter) and overrides configureMessageConverters should and will definitely be called. I recommend simply starting with the code samples of the article – I just tried it now and the method does get called. Hope that helps. Cheers,
      Eugen.

  • Shane

    Hello… i have declared a customer jacksonhttpmessageconverter and in special cases I don’t want it to run i.e. at certain known times don’t run the converter on my json.

    can i put an annotation on my controller method that returns the list to be json’d that basically allows the it to convert to json but doesn’t run my special converter?

    • Hey Shane – no, the framework doesn’t really allow you that degree of flexibility. You can’t actively select the Http converter at the controller level – you’ll need to write custom logic in order to handle your usecase. Cheers,
      Eugen.

  • Saisurya Kattamuri

    Hi eugen ,
    If we use message converter instead of we manually converting to json and return as responseentity (jsonAsString,httstatus code);of course we can avoid serializing everytime,but what I feel personally is we are loosing control over response status, I.e we can’t set multiple stats codes depending up on conditions, say 201 for created,4xx,5xx codes errors in the same controller method.the only way possible is httpservletresponse.set status code():,any other way we can manage this situation….
    Any help ?

    • If you allow the framework to resolve the status code instead of manually doing it – yes, you do lose a bit of control. That being said, there are good ways to still have full control over the status codes that you need to decide on yourself, while allowing the framework to do what it does best and use the defaults where they make sense.
      To have that control, take a look at this article. Hope it helps. Cheers,
      Eugen.

    • João Pedro Evangelista

      You can use ResponseEntity to return your entity as an object instead of a string, Spring will convert the entity to JSON and use the status code you added, also you have the ResponseStatus annotation for void methods or any other if you want.

  • Kisna

    Would you shed some light on performance overhead of the default message converter priority of checking many converters before landing on the XML/JSON converter. Especially in a high volume client that knows and talks only in JSON would prefer to move the JSON converter up to the top?

    Or even a custom RequestMappingHandlerAdapter with fasterxml on top

    And even the newer faster json serializers/deserializers?

    • Hey Kisna – 2 notes here. First – the checks are very basic operations, so they’re a minimal part of the overall processing logic of a request. That being said – if you know you’re not using some of the existing/default converters – it’s of course better to remove them and only have the ones that are actually in use.
      And next – there are a few good articles out there benchmarking JSON marshalling and unmarshalling – and Jackson usually has good marks compared to other JSON frameworks.
      Finally – if you’re dealing with very high-volume processing, it’s definitely worth trying out some scenarios once you have a solid battery of performance tests and a good metrics/monitoring solution in place.
      Hope that helps. Cheers,
      Eugen.

  • Johaness

    such uncomplete stuff like these cannot help anyone.

    • Hey Johaness – thanks for the feedback. Can you be a bit more specific – what would you like to see more information around, or what is it that’s missing? Cheers,
      Eugen.

  • russray2008

    Thank you for a nice article. I have beating my head against the wall trying to determine why using a RestTemplate was working for several methods but was not working for one method that was passing an object to add. I used your article to check my code and to determine what could I be possibly doing wrong. While it did not solve my issue, it did teach me another way of using HttpMessageConverters. Maybe I can get some feedback from you on what I could be doing wrong?

    Russ

    • Hey Russ,
      Sure, I’d be happy to have a look. A good way to go – especially with this code-heavy type of question – is to either open up an issue on Github (with the full details of what you’re trying to do), or a StackOverflow question. Then, just shoot me a quick email with the link. Cheers,
      Eugen.

      • russray2008

        Eugen,

        Hey… just wanted to say I got my issue fixed. Thanks for your suggestion about stack overflow.

        Russ

  • I finally got to look into the SO question and I see it’s already answers – which is quite cool. Of course, if you have any other issues, let me know. Cheers,
    Eugen.

  • springusr

    How can we use this in JMS. e.g. If I want to send customer object as xml , given my Customer.java has all jaxb annotation how can we do that ?
    Current code look like

    jmsTemplate.convertAndSend(“queue-name”, c); //c is customer object

    But this will send as serialize object. There must be way to hint to use converter. I tried something like this…

    • I haven’t looked at the JmsTemplate in quite a number of years so I don’t remember how the marshalling is done, but it’s definitely not going to use the HTTP message converters.
      Have a look at the reference as I assume the mechanism will be similar if you want to send your instance as is.
      Alternatively you can do the marshalling before you send and simply pass the raw data to your JMS template.
      Cheers,
      Eugen.

  • Robocide

    Good article , thank you ! , also notice that you are not actually loosing the default converters when extending WebMvcConfigurationSupport … you can invoke addDefaultHttpMessageConverters(..) function with your custom converters to add the default…

    • Yeah, I fully agree – it depends on how strict you want to be with your enabled converters. I used both approaches in the past, and I’m leaning towards not adding the defaults and only supporting the ones you want. But the alternative is certainly OK as well.
      Cheers
      Eugen.

  • harryajh

    really interesting article, I wonder if anyone has ever returned CSV from a Spring Rest API endpoint using jackson-dataformat-csv? so little docs on it (which probably means it should work pretty much out the box!), tried creating an @Component class extending AbstractHttpMessageConverter (should it be AbstractJackson2HttpMessageConverter?) but really not sure if this is the correct way?

    From the endpoint I “return ResponseEntity.ok(responseObject) which is a Pojo containing a List of objects I want written to the response body, really struggling to how to configure this correctly, all I want is an Spring enabled endpoint that produces “text/csv” via jackson’s CsvMapper

    any ideas/example links guys?

    • I would bet it’s been tried and done 🙂
      Unfortunately I never have, so I can’t be of much help on this one.
      Cheers,
      Eugen.

  • sammy

    From my restcontroller I want to access third party url which has headers set to force csv download.
    header(‘Content-type: text/csv’);
    header(‘Content-Disposition: attachment; filename=”abc.csv”‘);

    My rest controller will be called from javascript. Controller will do some extra validation and call third party url and return csv to UI if response status is 200.
    How can I achieve this. Using spring RestTemplate or anything else. What could be response type pass to restTemplate.getForObject.

    Can you please provide some sample code.

    • Right, so you basically need to support a CSV representation of your resources. That’s an interesting question, and I did do a relatively similar implementation many years ago, so there’s no reason it can’t be done. I just haven’t looked at it recently or focused on it specifically in an article here.
      But of course the same principles from this article apply.
      Hope that helps. Cheers,
      Eugen.

  • Robin Karlin

    In a Spring Boot MVC app is there a way to add a message converter to convert x-www-form-urlencoded request data to specific java objects such as those used in spring hateoas (eg Resource and Links)? I am able to post json formatted request data of this type via an ajax call but I also want to be able to do a form submit from a Thymeleaf template where my form th:object is of type org.springframework.hateoas.Resource.

    • Hey Robin – that’s an interesting usecase. Have a look at the FormHttpMessageConverter – but I haven’t tried it out for exactly that scenario, so you’ll have to look into it and see it it works. Also keep in mind that, if you don’t find a predefined converter, you can always just write your own.
      Hope that gives you enough info to move forward with the implementation. Cheers,
      Eugen.

  • PuneetHD

    How do I create a custom implementation of HttpMessageConverter to support YAML request/responses ?

    • PuneetHD

      I have solved it, Just need to create an implementation of AbstractHttpMessageConverter and register it using the WebMvcConfigurerAdapter#extendMessageConverters() method with Yaml jar classes.