1
{
    "0" : {
        "upc" : "00000000005",
        "name" : "Weighable Soup Cups",
        "location" : "5310ed21d5dc7aaa0343a932"
    },
    "1" : {
        "upc" : "00000000011",
        "name" : "OF Reuseable Bags",
        "location" : "5310ed21d5dc7aaa0343a932"
    }
}

Thats a snippet of the JSON I am trying to parse. Here is the code I am using:

public class Main {

    public static void main(String[] args) {

        JSONParser parser = new JSONParser();


        JSONObject jsonObject = null;
        try {
            jsonObject = (JSONObject) parser.parse("items.json");
        } catch (ParseException e) {
            e.printStackTrace();
        }

        JSONObject structure = (JSONObject) jsonObject.get("0");
        System.out.println(structure.get("upc"));



    }

}

For some reason throws an unexpected character (i) at position 0 error. As far as I know of the JSON file is formatted correctly for parsing and the code is solid, so I don't understand why this will not work. Thanks.

1 Answer 1

7

JSONParser#parse(String) expects a JSON string, not a file name.

You can use the overloaded method that expects a Reader and provide an InputStreamReader which wraps a FileInputStream.

jsonObject = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("items.json")));
Sign up to request clarification or add additional context in comments.

1 Comment

Or just a FileReader for simplicity.

Your Answer

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.