Don Don - 1 year ago 195
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.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()) {

} catch (FileNotFoundException e) {
} catch (IOException e) {
} catch (ParseException e) {



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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download