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");
Author by
RedEagle
Updated on June 15, 2022Comments
-
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 about 6 yearsThis 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 byCP1252
. Then you create a new String object out of these bytes and tell Java the bytes have to be interpreted asUTF-8
, even if the bytes areCP1252
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 withUTF-16
internally, but this doesn't matter). Encodings become important only when a String is converted to bytes.