spring-guides / getting-started-guides

Getting Started Guide template :: The template for new guides and also the place to request them.
https://github.com/spring-guides/getting-started-guides/wiki
Apache License 2.0
521 stars 204 forks source link

Consuming a RESTful Web Service doesn't has info about nested list in a JSON #54

Closed ghost closed 6 years ago

ghost commented 6 years ago

I'm currently working on a new spring based project and i had this problem again. It's very common (or for sure) consume APIs that the response looks like this:

{ id: 123, name: "foo", vehicles: [ { model: "sedan" }, { model: "truck" } ] }

In order to support the "vehicles" list attribute, you must define your RestTemplate Bean like this: `@Bean

public RestTemplate restTemplate(){
    RestTemplate restTemplate = new RestTemplate();
    MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.TEXT_HTML));
    restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
    return restTemplate;
}`

There's a lot of questions (like this) in stackoverlow .

I really think that if you're writing a new app, probably you'll need to parse nested json and it's a problem if the Guide only provide the basic feature of plain jsons. If you think that it's a good idea, i can help with the new lines of the Guide.

Thanks! Regards, Fede.

dsyer commented 6 years ago

That response is not JSON so it's not surprising it can't be unmarshalled using a JSON converter. What is this "embedded JSON" that you speak of? Where does it originate? Note that the SO link you pasted contains a question about unmarshalling actual JSON, so it doesn't look the same to me.

ghost commented 6 years ago

Thanks for the quick response! I already corrected the example JSON and the SO question link (isn't my question, is another guy question but in the same situation).

If you try to parse a JSON with a nested list of JSONs with the default RestTemplate configuration throws the exception:

Could not extract response: no suitable HttpMessageConverter found for response type

dsyer commented 6 years ago

Works for me. Maybe you can post a sample app? Perhaps fork the actual consuming guide that you referred to and modify it?

ghost commented 6 years ago

It was a problem of the server API, the response has the wrong content-type. I'll close the issue, thanks!.