Spring Boot-RestController反序列化YAML上传?
如何配置Spring Boot" title="Spring Boot">Spring Boot RestController接受YAML上传?
以下结果为415。通过调试,我可以看到MappingJackson2HttpMessageConverter
Spring上下文中的实例仅支持[application/json;charset=UTF-8,
application/*+json;charset=UTF-8]。我不能成为唯一尝试执行此操作的Spring Boot用户,但我感到惊讶的是它
不仅有效 -大多数操作都在Spring Boot中完成!
我的POM中有YAML数据格式:
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
我的RestController有这样一种方法:
@RequestMapping(method=RequestMethod.POST, value="/", consumes="application/yaml")public String upload(@RequestBody Declaration declaration) {
//Do stuff
}
而我的测试:
@Testpublic void triggersConvergence() throws Exception {
ClassPathResource fixture = new ClassPathResource("declaration.yml");
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Content-Type", "application/yaml");
requestHeaders.add("Accept", "application/json");
URI uri = new URI("http://127.0.0.1:"+port);
byte[] bytes = new byte[(int)fixture.contentLength()];
fixture.getInputStream().read(bytes);
RequestEntity<byte[]> postRequest = new RequestEntity<byte[]>(bytes, requestHeaders, HttpMethod.POST, uri);
ResponseEntity<String> response = rest.exchange(postRequest, String.class);
assertThat(response.getStatusCode(), is(HttpStatus.OK));
assertThat(response.getBody(), is("Converged org my-lovely-org"));
}
回答:
虽然此功能在Spring中不可用,但只需YAMLMapper
两个简单的步骤即可轻松添加它:
- 定义自己的
HttpMessageConverter
支持Content-Type: application/x-yaml
:
final class YamlJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter {YamlJackson2HttpMessageConverter() {
super(new YAMLMapper(), MediaType.parseMediaType("application/x-yaml"));
}
}
- 注册您的转换器:
@Configurationpublic class YamlConfiguration extends WebMvcConfigurerAdapter {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new YamlJackson2HttpMessageConverter());
}
}
享受从POJO 消费 和 生产的
控制器方法application/x-yaml
。
以上是 Spring Boot-RestController反序列化YAML上传? 的全部内容, 来源链接: utcz.com/qa/403780.html