In the first part we discussed the need to convert the Person instance into a comma separated format. By default Jackson throws the JSON formatted response. Let’s create a custom formatter class that will convert the Person object into comma separated format.
Creating a custom message converter is easy. We need to create the class that extends AbstractHttpMessageConverter and override it’s methods. The method that’s our concern is the writeInternal() method. A custom message converter is shown below.
public class CustomMessageConverter extends AbstractHttpMessageConverter<Person> { @Override protected boolean supports(Class<?> aClass) { if(Person.class.equals(aClass)) return true; return false; } @Override protected Person readInternal(Class<? extends Person> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException { return null; } public static final MediaType MEDIA_TYPE = new MediaType("text", "plain", Charset.forName("utf-8")); public CustomMessageConverter() { super(MEDIA_TYPE); } @Override protected void writeInternal(Person person, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException { String output = ""; output += person.getId() + "," + person.getName() + "," + person.getAge(); httpOutputMessage.getHeaders().setContentType(MEDIA_TYPE); final OutputStream out = httpOutputMessage.getBody(); out.write(output.getBytes(Charset.forName("utf-8"))); out.close(); } }
As you notice, the writeInternal() method does the required. We have generated the comma separated format and written it to the OutputStream. Now, we need to register this converter with the DispatcherServlet like this.
@EnableWebMvc @Configuration public class WebConfig extends WebMvcConfigurerAdapter{ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); converters.add(new CustomMessageConverter()); } }
And that’s it!!!. Send a request to the SampleController and you get the required output