'Trying to consume content-type [text/json] with Spring Boots's RestTemplate

A server is giving me a response in content-type text/json and I need to consume it into a Java class. I can do that no problem when the server's response is content-type application/json. How can I achieve the same functionality as when I consume an application/json content-type when I consume a text/json content type using Spring Boot?

I've tried creating an HttpHeaders object and then the setContentType method but as far as I've seen none of the MediaType options will work for 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 is the class that determines the servers response and Response is the Java representation of the returned json.

Ideally the returned json would be stored into the Response class but instead I am getting this error: InvocationTargetException: Failed to execute CommandLineRunner: Could not extract response: no suitable HttpMessageConverter found for response type [class Response] and content type [text/json]



Solution 1:[1]

You need to add the converter to the rest template. Please refer Answer 1 or Answer 2.

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rushi Daxini
Solution 2 Renato Manzoni