1

I have the below code in my program:

BufferedReader br = new BufferedReader(new InputStreamReader(
 urlConnection.getInputStream()));
Object obj = null;
try {
 obj = JSONValue.parse(br);
} catch (Exception e) {
 System.out.println(e);
}
response = obj.toString();

The problem is that it's not converting chars like \u... to normal chars. For example i get:

caffË instead of caffè felicit\u2021 instead of felicità

I'm actually using the json-simple api: http://alex-public-doc.s3.amazonaws.com/json_simple-1.1/index.html.

The url connection is to a page that send me a json file.

Any suggest?

Batakj
12.8k17 gold badges68 silver badges114 bronze badges
asked May 31, 2013 at 8:47
4
  • 2
    Did you try new InputStreamReader(urlConnection.getInputStream(), "UTF-8")? Commented May 31, 2013 at 8:50
  • I tried your solution and now all the \u.... chars are converted into "?" Commented May 31, 2013 at 8:56
  • works for me. what's exactly your input string? Commented May 31, 2013 at 9:26
  • try passing -Dfile.encoding="UTF-8" to java. Commented May 31, 2013 at 9:27

1 Answer 1

4

You need to initialize the input stream reader with UTF charset. Here is what you need to update:

BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
answered May 31, 2013 at 8:53
Sign up to request clarification or add additional context in comments.

5 Comments

I tried this, now i'm getting all "?" chars instead of the \u... chars
Are you printing it on console? If yes then FYI, console wouldnt be able to render your utf-8 output properly
I'm not only printing them on console, but also writing them on a txt file and uploading to a mysql database with utf-8 charset properly set.
Are you writing them as UTF-8? FileWriter, for example, takes the OS default encoding, which is NOT UTF-8 if you are on Windows. You have to do the same trick to write as you did to read.
The default character encoding in Java for Mac OS X is MacRoman, see this: en.wikipedia.org/wiki/Mac_OS_Roman#Application_notes

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.