Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json-simple utf-8 parsing in Java

I'm trying to parse JSON using json-simple-1.1.1

public static void main(String[] args) throws ParseException, IOException{

    BufferedReader buff = new BufferedReader(new FileReader("src/qqqqqqqq/json"));

    String line = null;

    while((line = buff.readLine()) != null){

        JSONParser parser = new JSONParser();
        Object obj = (Object) parser.parse(line);
        JSONObject jsonObj = (JSONObject) obj;

        System.out.println((String)jsonObj.get("name"));
    }
}

My JSON source file using UTF-8 without BOM

{"name":"ą"}
{"name":"ć"}
{"name":"ń"}
{"name":"ź"}
{"name":"ż"}
{"name":"ó"}

Output from println:

Ä…
ć
Ĺ„
Ĺş
ĹĽ
Ăł

What I am doing wrong?

like image 657
Piotr K. Avatar asked Oct 19 '22 19:10

Piotr K.


1 Answers

A FileReader uses the default charset which must not be UTF-8.

Use

new BufferedReader(new InputStreamReader(new FileInputStream("src/qqqqqqqq/json"), "UTF-8"));

instead.

like image 88
wero Avatar answered Oct 23 '22 07:10

wero