RKodakandla
RKodakandla

Reputation: 3494

Special characters encoding in JSON response

I need to spend Spanish text in json response. I have tried all the possible ways but the message still shows weird characters on the UI. The message I want to show is,

   Número de Seguro Social

But it shows up as,

    N�mero de Seguro Social 

On the Java side,

 //response.setContentType("application/json");
 //response.setCharacterEncoding("UTF-8");
 response.setContentType("application/json;charset=utf-8");
 OutputStream out = null;
 out = response.getOutputStream();
 out.write(jsonResponse.toString().getBytes());
 out.close();

added meta tag in head section.

  <meta http-equiv="content-type" content="text/html;charset=utf-8">

I have also set the content type in ajax call

 $.ajax({
      async: false,
      cache: false,
      type: get,
      contentType: "application/json; charset=utf-8",
      url: //url,
      data: //data,
      dataType: //dataType,
      success: //callbackfn,
      error: //errorfn
  });

Nothing seem to work. Is there anything else I can do to get the special characters work as I intended?

Upvotes: 2

Views: 10240

Answers (2)

bala
bala

Reputation: 11

$.ajax({
type: "Get",
url: your url,
data: { inputParam : JSON.stringify(inputParam)},
    dataType: "json",
    success: //callbackfn,
    error: //error
});

Upvotes: 0

Danack
Danack

Reputation: 25721

I would test where the error is occurring first by sending the string:

 "N\u00famero de Seguro Social"

To the browser that is showing the UTF string, just to make sure that it is capable of understanding and displaying the UTF string you're trying to display.

But the actual problem is probably in:

out.write(jsonResponse.toString().getBytes());

As getBytes will get the bytes for the default charset for the system, which may not be UTF-8. You can check this by calling Charset.defaultCharset();

I'm guessing jsonResponse is your own class for storing the response data and then converting it to JSON at the end. I'd recommend using a library from http://www.json.org/ like the Google JSON library for doing the JSON conversion, as there are lots of little gotchas like this one, that are solved problems, so long as you use a decent library to do the encoding/decoding.

Upvotes: 3

Related Questions