3

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]

user728
  • 51
  • 3

2 Answers2

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

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);
Rushi Daxini
  • 1,570
  • 1
  • 10
  • 14
  • 1
    I assume that this would work with content-type `text/plain` as in the first [link](https://stackoverflow.com/questions/49469954/force-spring-resttemplate-to-process-plain-text-as-json) you provided by using `MediaType.TEXT_PLAIN`, but I am needing to consume the content-type `text/json`. I'm hoping Spring Boot has the functionality to do so. – user728 Jul 30 '19 at 15:08