Search code examples
javajsonutf-8character-encodingresttemplate

Java Spring resttemplate character encoding


I'm using the Java Spring Resttemplate for getting a json via a get request. The JSON I'm getting has instead of special character slike ü ö ä or ß some weird stuff. So I guess somethings wrong with the character encoding. I can't find any help on the internet. The code I'm using for now is:

String json = restTemplate.getForObject(
    overPassStatementPostCode,
    String.class,
    params);

Solution

  • You just need to add the StringHttpMessageConverter to the template's message converters:

    RestTemplate template = new RestTemplate();
    template.getMessageConverters()
            .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
    ResponseEntity<Object> response = template.exchange(endpoint, method, entity, 
                                                        Object.class);