2016-11-08 72 views
0

我想讀取使用Java JSONParser的Json文件中的兩個對象,但在解析Json文件時遇到了以下問題。我提供了Java代碼和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" 
    } 
} 
+0

您是否使用任何在線工具驗證了您的JSON? '} {'不正確。我喜歡jsonlint – AxelH

+1

你的json文件無效:它包含2個json對象。 – pozs

回答

0

您發送的不是JSON正確的。它由2個JSON對象組成,一個接一個是非法的。要麼你必須在JSONArray中添加兩個對象,從數組中獲取單個對象並對其進行處理。 或者你可以將Json字符串拆分爲「} {」,然後將其轉換爲json對象以供進一步計算。

P.S.我知道第二種方法很骯髒,但這可能會讓某個人變成一天。

+0

如果你在'} {'分割,除非你將這些字符加回去,否則它仍然是無效的 –

+0

這是非常瞭解的東西。我的回答只是指示 –

+0

不是每個人都能理解JSON格式(這個問題很明顯),所以我想我會明確地說 –