【发布时间】:2019-10-09 11:39:21
【问题描述】:
即使添加了在其他解决方案中在线找到的所有代码(我添加了 HttpMessageConverters 以及 APPLICATION_JSON 接受标头),我仍然在标题中遇到异常。
public MyObject myMethod(String arg) {
String uri = BASE_URI + "/var?arg=" + arg;
restTemplate.setMessageConverters(getMessageConverters());
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<MyObject> response = restTemplate.exchange(uri, HttpMethod.GET, entity, MyObject.class);
MyObject resource = response.getBody();
return resource;
}
private List<HttpMessageConverter<?>> getMessageConverters() {
List<HttpMessageConverter<?>> converters =
new ArrayList<>();
converters.add(new MappingJackson2HttpMessageConverter());
converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
return converters;
}
我的对象:
public class MyObject {
private String test;
//more fields
@JsonCreator
public MyObject(String test) { //more args
this.test = test;
//more assignments
}
有人知道吗?
编辑:pom.xml 中的相关依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
【问题讨论】:
-
嗨,Tiberiu,您是否使用
spring-boot?如果您使用的是 spring boot,则不需要添加这些消息转换器。请在pom.xml或build.gradle中提供一些有关依赖项的信息。 -
在
pom.xml中添加了相关依赖
标签: spring-boot jackson resttemplate