简体   繁体   中英

Java - Json File Parser issue

I am trying to read two objects in Json file using Java JSONParser but I am getting a below issue while parsing a Json file. I have provided Java code and Json file content for your reference.

Issue:

Unexpected token LEFT BRACE({) at position 286.
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)

Java Code:

    public static void main(String[] args) throws Throwable {
        JSONParser  parser = new JSONParser();
         JSONObject a = null;
         Connection con = null;
         Statement stmt = null;
        try {
            Object obj = parser.parse(new FileReader("C:\\Users\\mhq175\\workspace2\\JCucumber\\JSON_FILES\\Datafile.json"));
            JSONObject jsonObject = (JSONObject) obj;
            JSONObject structure = (JSONObject) jsonObject.get("MessageContext");
            JSONObject structure_2 = (JSONObject) jsonObject.get("MessageContext1");
            con = postconn.getConnection();
            String entireFileText = "INSERT INTO Events"
                       + " VALUES ('"+ structure + "','"+ structure_2 + "');";
            System.out.println(entireFileText); 
            stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
             stmt.executeUpdate(entireFileText);
    }   catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

Json File:

{
    "MessageContext": {
        "field1": "VALUE1",
        "field2": "VALUE2",
        "field3": "VALUE3",
        "field4": "VALUE4",
        "field5": "VALUE5"
    },
    "MessageContext1": {
        "field1": "VALUE1",
        "field2": "VALUE2",
        "field3": "VALUE3",
        "field4": "VALUE4",
        "field5": "VALUE5"
    }
}{
    "MessageContext": {
        "field1": "VALUE1",
        "field2": "VALUE2",
        "field3": "VALUE3",
        "field4": "VALUE4",
        "field5": "VALUE5"
    },
    "MessageContext1": {
        "field1": "VALUE1",
        "field2": "VALUE2",
        "field3": "VALUE3",
        "field4": "VALUE4",
        "field5": "VALUE5"
    }
}

The JSON you are sending in not correct. It consist of 2 JSON object one after another which is illegal. Either you have to add both object in JSONArray, get individual object from array and manipulate it. Or you can split Json string at "}{" and then convert it to json object for further calculation.

PS i know the second approach is dirty but this could make make someone day.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM