I am looking for a quick/easy solution how to automatically serialize Rest controllers output to CSV instead of JSON. I have the simplest possible Spring boot application:
@SpringBootApplication
public class CsvExportApplication {
public static void main(String[] args) {
SpringApplication.run(CsvExportApplication.class, args);
}
}
class User {
String name;
String surname;
public User(String name, String surname) {
this.name = name;
this.surname = surname;
}
public void setName(String name) {
this.name = name;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
}
@RestController
class UserController {
@GetMapping(value = "/users")
List<User> list() {
return Arrays.asList(new User("adam", "kowalsky"), new User("john", "smith"));
}
}
I have used jackson-dataformat-csv
and came up with the following code that serializes List<User>
to String
, but ideally I do not want to change the rest controller code:
CsvMapper mapper = new CsvMapper();
CsvSchema schema = mapper.schemaFor(User.class).withHeader();
mapper.writerFor(List.class).with(schema).writeValueAsString(users);
Ideally I would like my controllers to be able to return output in JSON or CSV depending on the Accept header in the request.