You have a Spring Boot service that sends out an Object as response. The Object is automatically converted to JSON response, thanks to Jackson parser in the classpath. Let’s look at the service below. It’s a simple service that accepts an id of a person as argument, and returns a person instance.
@RestController public class SampleController { @RequestMapping(value="/{id}") public Person getPerson(@PathVariable("id") long id){ //Look up the DB and fetch the person //Let's hardcode that for now Person person = new Person(); person.setId(id); person.setName("John"); person.setAge(40); return person; } }
The Person class is a simple POJO with id, name and age properties as shown below.
public class Person { private String name; private int age; private long id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public long getId() { return id; } public void setId(long id) { this.id = id; } }
When you run this as http://localhost:8080/101, Jackson converts the Person instance to JSON and gives you this output.
{"name":"John","age":40,"id":101}
But say, you want to convert it to CSV format or JSON format with some other parser like GSON, here’s where custom converters come into picture. Let’s try to convert Person instance to this format.
101,John,40
We’ll now create a custom HttpMessageConverter and plug it in. And that involves creating a couple of classes.
[…] the first part we discussed the need to convert the Person instance into a comma separated format. By default […]