gpt4 book ai didi

java - Spring Boot - RestController 反序列化 YAML 上传?

转载 作者:搜寻专家 更新时间:2023-11-01 02:04:41 25 4
gpt4 key购买 nike

如何配置 Spring Boot RestController 以接受 YAML 上传?

以下结果为 415。我可以从调试中看到我的 Spring 上下文中的 MappingJackson2HttpMessageConverter 实例仅支持 [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
}

还有我的测试:

@Test
public 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 轻松添加只需 2 个简单的步骤:

  1. 定义你自己的HttpMessageConverter支持 Content-Type: application/x-yaml :

    final class YamlJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter {
    YamlJackson2HttpMessageConverter() {
    super(new YAMLMapper(), MediaType.parseMediaType("application/x-yaml"));
    }
    }
  2. 注册您的转换器:

    @Configuration
    public class YamlConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(new YamlJackson2HttpMessageConverter());
    }
    }

享受 Controller 方法消费生产 application/x-yaml来自 POJO。

关于java - Spring Boot - RestController 反序列化 YAML 上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37328314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com