尝试使用Spring Boot的RestTemplate消费文本/JSON类型的内容

3
服务器返回的是 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 则是 Java 对返回的 JSON 的表示。

理想情况下,返回的 JSON 数据会被存储到 Response 类中。但是,我遇到了以下错误:InvocationTargetException: Failed to execute CommandLineRunner: Could not extract response: no suitable HttpMessageConverter found for response type [class Response] and content type [text/json]

2个回答

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

0

您需要将转换器添加到RestTemplate中。请参考答案1答案2

MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON));
restTemplate.getMessageConverters().add(0, converter);

1
我假设使用MediaType.TEXT_PLAIN作为content-type,可以像你提供的第一个链接中那样正常工作,但是我需要消耗text/json类型的内容。我希望Spring Boot有相关的功能可以实现这一点。 - user728

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接