JAX-RS Encoding

11,879

Solution 1

I ended up using GSON instead of IBM's JSON4J which proved to be much better at handling custom Java class serialization.

Solution 2

All you need is this:

String back = "Depósitos";
return new String(back.getBytes(), "UTF8");
Share:
11,879
RedEagle
Author by

RedEagle

Updated on June 15, 2022

Comments

  • RedEagle
    RedEagle almost 2 years

    I'm using JAX-RS to create a web (rest) service that returns results in JSON format.

    Everything is OK, except the encoding.

    For example, I get:

     ..., parameter:"Dep\u00f3sitos" ,...
    

    Instead of:

     ..., parameter:"Depósitos" ,...
    

    I've tried using:

    @Produces("application/json; charset=UTF-8")
    

    but the problem remains. If I return it as XML using just:

    @Produces("application/xml")
    

    Everything is ok.

    What do I need to set to produce the right type?

  • Sky
    Sky about 6 years
    This is useless and dangerous code. String.getBytes() converts the string to the platform's default encoding. Let's say you are on Windows, so this might by CP1252. Then you create a new String object out of these bytes and tell Java the bytes have to be interpreted as UTF-8, even if the bytes are CP1252 text in this example, which will lead to problems. Further: back is already a String, Java String objects can be seen as text without encoding (they are encoded with UTF-16 internally, but this doesn't matter). Encodings become important only when a String is converted to bytes.