Don Don - 3 months ago 23
Java Question

Error reading json file in java

I searched for this issue on the site but couldn't find one. May I know what am I missing here?

package com.json;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonTest {

public static void main(String[] args) {

JSONParser parser = new JSONParser();

try {

Object obj = parser.parse(new FileReader("E://file.json"));

JSONObject jsonObject = (JSONObject) obj;

String nameOfCountry = (String) jsonObject.get("Name");
System.out.println("Name Of Country: "+nameOfCountry);

long population = (Long) jsonObject.get("Population");
System.out.println("Population: "+population);

System.out.println("States are :");
JSONArray listOfStates = (JSONArray) jsonObject.get("States");
Iterator<String> iterator = listOfStates.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}

}
}





{"Name":"EX","Population":1000000,"States":["MP","MH","RN"]}




Error: Unexpected character (ï) at position 0.
at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:92)

Answer

The error message show a weird character ï at position 0.

Your JSON file has a UTF-8 BOM (byte order mark), which starts with byte EF, that in code page ISO-8859-1 is the ï character.

Save your JSON file in ISO-8859-1, i.e. not in UTF-8. Java API's don't support BOM's.

Alternatively, save in UTF-8 without a BOM, and read in Java as UTF-8.

Comments