Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

Making one type of object out of another is a common need in programming, especially when it comes to communication and messages.

In this tutorial, we’ll learn how to configure HttpMessageConverters in Spring. Simply put, we can use message converters to marshal and unmarshal Java Objects to and from JSON and XML 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.

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.

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.

2. The Basics

Before delving into specifics, let’s set up and look at the necessary requirements.

2.1. Enable Web MVC

To begin with, a web application should be configured with Spring MVC support. For instance, 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 {
    
    // ...
    
}

Notably, this class implements WebMvcConfigurer, which enables changing the default list of HTTP converters.

2.2. Default Message Converters

By default, there is a number of pre-enabled HttpMessageConverters:

  • 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 data to or from a MultiValueMap<String, String>
  • Jaxb2RootElementHttpMessageConverter converts Java objects to or 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)

All of these can come in handy, depending on the case. However, knowing how and when to apply them is critical.

3. Client-Server Communication – JSON Only

Now, let’s understand how to ensure the proper JSON object transfer between client and server.

3.1. High-Level Content Negotiation

Each HttpMessageConverter implementation has one or several associated MIME types. When receiving a new request, Spring performs several steps:

  • use the Accept header to determine the media type that it needs to respond with
  • try to find a registered converter capable of handling that specific media type
  • employ this converter to convert the entity and send back the response

Moreover, the process is similar for receiving a request that contains JSON information:

  • use the Content-Type header to determine the media type of the request body
  • search for an HttpMessageConverter that can convert the body sent by the client to a Java object
  • perform the conversion and send back

So, let’s clarify these flows with a quick example:

  1. The Client sends a GET request to /foos, with the Accept header set to application/json, to get all Foo resources as JSON.
  2. The Foo Spring Controller is hit, and returns the corresponding Foo Java entities.
  3. Then Spring uses one of the Jackson message converters to marshal the entities to JSON.

So, let’s 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 is used to choose the appropriate HTTP converter to marshal the entity:

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

Now, the client specifies the Accept header to application/json in the request:

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

Let’s see a sample Foo class:

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

Based on this, we can imagine an expected HTTP response body:

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

Thus, marshaling happens based on the initial template class.

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 uses the Content-Type header from the client request:

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

Next, we consume this with a JSON object, specifying the 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

Let’s see the response:

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

Of course, we should get back a 200 OK, a success.

4. Custom Converters Configuration

Sometimes, we might want to add additional functionality to existing message converters.

4.1. Customization

Let’s 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<?>> messageConverters) {
        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;
    } 
}

In this example, we’re creating a new converter, the MarshallingHttpMessageConverter, and using the Spring XStream support to configure it. This enables 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 it however we want.

Notably, this example requires adding the XStream library to the classpath.

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

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

In this case, XStream was the selected marshaller and unmarshaller implementation, but others, like JibxMarshaller, 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

Thus, we have a custom converter.

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

Instead, we can just define different HttpMessageConverter beans in the context, and Spring Boot adds them automatically to the autoconfiguration that it creates:

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

    // ...

    return xmlConverter;
}

This way, we save a lot of targeted edits.

4.3. HttpMessageConverters Builder

Starting with Spring Framework 7.0 and Spring Boot 4, configuring message converters has become easier with the introduction of the HttpConvertersConfig class. This new approach provides a builder-based API and enables a type-safe configuration.

Instead of directly manipulating a list of converters, configureMessageConverters() in WebMvcConfigurer now accepts an HttpMessageConverters.ServerBuilder parameter.

Let’s use this feature to configure customized JSON and XML converters for the application:

@Configuration
class HttpConvertersConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(HttpMessageConverters.ServerBuilder builder) {
        JsonMapper jsonMapper = JsonMapper.builder()
          .findAndAddModules()
          .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
          .enable(JsonReadFeature.ALLOW_SINGLE_QUOTES)
          .defaultDateFormat(new SimpleDateFormat("yyyy-MM-dd"))
          .build();

        XmlMapper xmlMapper = XmlMapper.builder().findAndAddModules()
          .enable(XmlReadFeature.EMPTY_ELEMENT_AS_NULL)
          .defaultDateFormat(new SimpleDateFormat("yyyy-MM-dd")).build();

        builder.jsonMessageConverter(new JacksonJsonHttpMessageConverter(jsonMapper))
          .xmlMessageConverter(new JacksonXmlHttpMessageConverter(xmlMapper));
    }
}

As we can see, we leverage the HttpMessageConverters.ServerBuilder to configure multiple converters in a declarative fashion.

5. Using Spring RestTemplate With HTTP Message Converters

In addition to the server-side, HTTP message conversion can be configured on the client side of the Spring RestTemplate.

In particular, we first configure the template with the Accept and Content-Type headers when appropriate. Then, we try to consume the REST API with full marshalling and unmarshalling of the Foo resource, both with JSON and XML.

5.1. Retrieving the Resource With No Accept Header

To start, let’s write a simple test:

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

    RestTemplate restTemplate = new RestTemplate();
    Foo resource = restTemplate.getForObject(URI, Foo.class, "1");

    assertThat(resource, notNullValue());
}

This way, we try a basic retrieval and ensure the result.

5.2. Retrieving a Resource With application/xml Accept Header

Now, let’s explicitly retrieve the resource as an XML representation. For that, we also define a set of converters and set these on the RestTemplate.

Because we’re consuming XML, we 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(getXmlMessageConverters());

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

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

    assertThat(resource, notNullValue());
}

private List<HttpMessageConverter<?>> getXmlMessageConverters() {
    XStreamMarshaller marshaller = new XStreamMarshaller();
    marshaller.setAnnotatedClasses(Foo.class);
    MarshallingHttpMessageConverter marshallingConverter = 
      new MarshallingHttpMessageConverter(marshaller);

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

At this point, we have a simplified object conversion.

5.3. Retrieving a Resource With application/json Accept Header

Similarly, we can 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(getJsonMessageConverters());

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(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<?>> getJsonMessageConverters() {
    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(new MappingJackson2HttpMessageConverter());
    return converters;
}

Same as the XML example, we use the appropriate converter.

5.4. Update a Resource With XML Content-Type

Finally, we send XML 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";
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(getJsonAndXmlMessageConverters());

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

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

    assertThat(fooResponse, notNullValue());
    assertEquals(resource.getName(), fooResponse.getName());
}

private List<HttpMessageConverter<?>> getJsonAndXmlMessageConverters() {
    List<HttpMessageConverter<?>> converters = getJsonMessageConverters();
    converters.addAll(getXmlMessageConverters());
    return converters;
}

What’s interesting here is that we can mix the media types. Specifically, 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 article, we learned how Spring MVC enables us to specify and fully customize HTTP message converters to automatically marshal and unmarshal Java entities to and from XML or JSON. This is, of course, a simplistic definition, and there’s so much more that the message conversion mechanism can do, as we can see from the last test example.

In addition, we 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 code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW