8

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?

Charles Stewart
  • 11,661
  • 4
  • 46
  • 85
RedEagle
  • 4,418
  • 9
  • 41
  • 64

3 Answers3

1

All you need is this:

String back = "Depósitos";
return new String(back.getBytes(), "UTF8");
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Frank
  • 11
  • 1
  • 1
    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. – Sky Mar 06 '18 at 16:46
1

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

Nathan
  • 8,093
  • 8
  • 50
  • 76
RedEagle
  • 4,418
  • 9
  • 41
  • 64
0

Take a look at Bryant Luk's answer to the question "How to set the charset with JAX-RS?" and see if it does the trick.

Community
  • 1
  • 1
bamana
  • 1,625
  • 12
  • 15