Search code examples
jsonspringjacksonspecial-charactersresttemplate

Passing special characters like E acute to JSON webservice using RestTemplate


I am getting data from database and calling the rest json webservice. I am using spring restTemplate to call the webservice. I have added jackson jar which is being used by spring to create json. However , I face issue when we get characters like latin e with acute É. Jackson don't escape it and passed as it is, here webservice fails at other end gives 500 internal error. I need to pass its unicode like \u0209. I tried using the StringEcapeUtils to convert it , it got converted to \u0209. But this time RestTemplate escapes it again as \u0209 and it got received as \u0209 on the target system.

Target system is another system we cannot change anything there.

My code for restTemplate is :-

MultiValueMap<String, String> headers =
        new LinkedMultiValueMap<String, String>();
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE); //Note Content-Type as opposed to Accept

        HttpEntity<Object> entity = new HttpEntity<Object>(myRequest, headers);

        myResponse = restTemplate.postForObject(url, entity, responseClass );

Solution

  • I'm guessing the server doesn't know how to interpret what you're sending. Have you tried

    MediaType mediaType = 
        new MediaType( "application" , "json" , Charset.forName( "UTF-8" ) ); 
    headers.add( "Content-Type", mediaType );
    

    Cheers,