java - 尝试使用 Spring Boots 的 RestTemplate 来使用内容类型 [text/json]

标签 java json spring rest spring-boot

服务器正在以内容类型 text/json 的形式向我提供响应,我需要将其使用到 Java 类中。当服务器的响应是内容类型 application/json 时,我可以毫无问题地做到这一点。当我使用 Spring Boot 使用 text/json 内容类型时,如何实现与使用 application/json 内容类型时相同的功能?

我尝试创建一个 HttpHeaders 对象,然后创建 setContentType 方法,但据我所知,没有任何 MediaType 选项适用于 text/json

Request req = new Request();
String url = "<url>";

HttpHeaders headers = new HttpHeaders();
headers.setContentType( MediaType.TEXT_JSON ); // this isn't valid but is where I have tried setting the content-type to text/json
HttpEntity< Request > entity = new HttpEntity<>( req, headers );
ResponseEntity< Response > resp = 
    restTemplate.exchange( url, HttpMethod.POST, entity, Response.class );

Request 是确定服务器响应的类,Response 是返回的 json 的 Java 表示形式。

理想情况下,返回的 json 将存储到 Response 类中,但我收到此错误:InitationTargetException:无法执行 CommandLineRunner:无法提取响应:没有找到适合响应的 HttpMessageConverter类型 [class Response] 和内容类型 [text/json]

最佳答案

MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(new MediaType("text","json")));
restTemplate.getMessageConverters().add(0, converter);

关于java - 尝试使用 Spring Boots 的 RestTemplate 来使用内容类型 [text/json],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57261703/

相关文章:

java - Spring Boot Hibernate高效事务管理

java - 使用 Firebird 将日期转换为时间戳

java - 如何在 ListView 中仅显示一列数据?

json - Swift,错误(参数标签 '(node:)' 与任何可用的重载不匹配),rest in Vapor,模型 Controller

java - Spring Boot Raw WebSocket 设置主体

java - Spring Security 缓存我的身份验证

java - 从java中的csv列添加: how do I reset variable total?

json - Golang JSON 序列化/反序列化

Javascript 无法解析 JSON 字符串

java - 添加elasticsearch支持后,Spring Boot提示 BeanCreationException 与嵌套的 IllegalStateException 未找到关联