Search code examples
javajsonutf-8byte-order-mark

Reading .json file - BOM issue?


I need to read a .json file and change a field in runtime.

The problem is when I try to read it:

JSONObject jOb=null;


        try {
            jOb = new JSONObject(filePath);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println(jOb.toString());
        try {
            jOb.put("responseType", "TESTicles");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println(""+jOb);

I get the following error: "A JSONObject text must begin with '{' at 1 [character 2 line 1]"

I think the problem might be the BOM marker because my file starts with '{'

Here's a sample (the beginning of my json file):

{
  "base":{    
    "sites":{
      "local":{
        "name":"siteA",
        "datasource":{
...

I need to remove the BOM marker in order to read the file but how can I do it without reading the file?

I've read:

This, this and many other stuff about it, but I can't seem to find any solution to my problem. What can I do?


Solution

  • On the assumption that you are using the library defined at json.org, what your code does is treat the file name as a JSON string and try to interpret it as a JSON object.

    Reading the docs, you'll need to open the file as an input stream, pass it as a parameter in a JSONTokener constructor which you pass as a parameter to your JSONObject constructor, something like:

    InputStream foo = new FileInputStream(filePath);
    JSONTokener t = new JSONTokener(foo);
    JSONObject obj = new JSONObject(t);
    

    Note: the above not tested or even compiled.