Java - Json File Parser问题

时间:2016-11-08 15:06:32

标签: java json parsing

我正在尝试使用Java JSONParser在Json文件中读取两个对象,但在解析Json文件时遇到了以下问题。我提供了Java代码和Json文件内容供您参考。

问题:

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代码:

    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文件:

{
    "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"
    }
}

1 个答案:

答案 0 :(得分:0)

您发送的JSON不正确。它由一个接一个的2个JSON对象组成,这是非法的。您必须在JSONArray中添加两个对象,从数组中获取单个对象并对其进行操作。 或者您可以将Json字符串拆分为"} {"然后将其转换为json对象以进行进一步计算。

P.S。我知道第二种方法很脏,但这可能会让某人成为一天。