Configuring a custom HttpMessageConverter in SpringBoot

The HttpMessageConverter provides a convenient way to add and merge additional converters in a web application. In this tutorial we will learn how to specify an additional HttpMessageConverter and add it to the default ones.

Here is an example class, which provides as additional HtpMessageConverter the MarshallingHttpMessageConverter:

package com.example.testrest;

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.oxm.xstream.XStreamMarshaller;

@Configuration
public class MyConfiguration {
  @Bean
  public HttpMessageConverters customConverters() {
    MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
    XStreamMarshaller xstream = new XStreamMarshaller();
    xmlConverter.setMarshaller(xstream);
    xmlConverter.setUnmarshaller(xstream);
    return new HttpMessageConverters(xmlConverter);
  }
}

The MarshallingHttpMessageConverter uses as marshaller/unmarshaller the XStreamMarshaller. The XStreamMarshaller has the capability to convert from/to XML any Java class without adding annotations to it.

In our case, we will use it to marshall/unmarshall the following Java Bean class:

public class Customer {
  private int id;
  private String name;

  public Customer(int id, String name) {
    super();
    this.id = id;
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }
}

Here is out Controller class:

@RestController
public class CustomerController {
  @Autowired CustomerRepository repository;

  @RequestMapping(value = "/list", method = RequestMethod.GET)
  public List<Customer> findAll() {
    return repository.getData();
  }

  @RequestMapping(value = "/one/{id}", method = RequestMethod.GET)
  public Customer findOne(@PathVariable int id) {
    return repository.getData().get(id);
  }
}

You can see the effect of the marshaller. When requesting the Customer list:

curl --header "Accept: application/xml" http://localhost:8080/list  
<list>
	<com.example.testrest.Customer>
		<id>1</id>
		<name>frank</name>
	</com.example.testrest.Customer>
	<com.example.testrest.Customer>
		<id>2</id>
		<name>john</name>
	</com.example.testrest.Customer>
</list> 

On the other hand, you can still request the list of Customer as JSON:

curl --header "Accept: application/json" http://localhost:8080/list [{"id":1,"name":"frank"},{"id":2,"name":"john"}]

Source code for this tutorial: https://github.com/fmarchioni/masterspringboot/tree/master/mvc/custom-converter

 

Found the article helpful? if so please follow us on Socials
Twitter Icon       Facebook Icon       LinkedIn Icon       Mastodon Icon