Question

How can I use Spring RestTemplate to get GeoJson into my controller? I need it to get GeoJson to my controller so I can pass it to a view where I will draw it on a map.

I tested it with String and get for object like so:

String featureCollection = restTemplate.getForObject(geoJsonUrl, String.class);

It works for now but what is a better way of doing so?

Was it helpful?

Solution

I'm not aware of a RestTemplate message converter that directly supports GeoJson. However, you can try to use MappingJackson2HttpMessageConverter to consume the resource as a Jackson JsonNode. Then it will be easier to traverse the json structure.

JsonNode featureCollection = restTemplate.getForObject(geoJsonUrl, JsonNode.class);

By default MappingJackson2HttpMessageConverter only supports the application/json media type. If the server is setting a different Content-type, then you may need to specify that. For example, the following sets the supported media type to text/javascript:

MappingJackson2HttpMessageConverter jackson = new MappingJackson2HttpMessageConverter();
jackson.setSupportedMediaTypes(Collections.singletonList(new MediaType("text", "javascript")));
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(jackson);
RestTemplate restTemplate = new RestTemplate(converters);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top