我正在寻找一种快速/简便的解决方案,如何将Rest控制器的输出自动序列化为CSV而不是JSON。我有最简单的Spring引导应用程序:
@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"));
}
}
我用过jackson-dataformat-csv
,并想出了以下代码将List<User>
序列化为String
,但是理想情况下,我不想更改其余的控制器代码:
CsvMapper mapper = new CsvMapper();
CsvSchema schema = mapper.schemaFor(User.class).withHeader();
mapper.writerFor(List.class).with(schema).writeValueAsString(users);
理想情况下,我希望我的控制器能够根据请求中的Accept标头以JSON或CSV返回输出。
答案 0 :(得分:1)
我设法通过以下方式实现自己想要的目标:
ObjectMapper
(以确保CSV和JSON输出使用例如相同的日期格式)jackson-dateformat-csv
模式:https://github.com/FasterXML/jackson-dataformats-text/issues/114 代码:
class CsvConverter<T> extends AbstractHttpMessageConverter<T> {
private final ObjectMapper objectMapper;
CsvConverter(ObjectMapper objectMapper) {
super(new MediaType("application", "csv"));
this.objectMapper = objectMapper;
}
@Override
protected boolean supports(Class<?> clazz) {
return true;
}
@Override
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
return null;
}
@Override
protected void writeInternal(T object, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
try {
ObjectWriter objectWriter = getCsvWriter(object);
try (PrintWriter outputWriter = new PrintWriter(outputMessage.getBody())) {
outputWriter.write(objectWriter.writeValueAsString(object));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
ObjectWriter getCsvWriter(T object) {
Set<String> fields = getUniqueFieldNames(object);
CsvSchema.Builder schemaBuilder = CsvSchema.builder().setUseHeader(true);
for (String field : fields) {
schemaBuilder.addColumn(field);
}
return new CsvMapper().writerFor(List.class).with(schemaBuilder.build());
}
Set<String> getUniqueFieldNames(T object) {
try {
JsonNode root = objectMapper.readTree(objectMapper.writeValueAsString(object));
Set<String> uniqueFieldNames = new LinkedHashSet<>();
root.forEach(element -> {
Iterator<String> it = element.fieldNames();
while (it.hasNext()) {
String field = it.next();
uniqueFieldNames.add(field);
}
});
return uniqueFieldNames;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
@Configuration
class AppConfig implements WebMvcConfigurer {
private final ObjectMapper objectMapper;
AppConfig(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new CsvConverter<>(objectMapper));
}
}