2016-08-30 54 views
-1

目標:將JSONArray數據追加到外部.json文件中的現有JSONArray。無法正確使用JSON格式將JSON格式化爲.json文件使用JSON.Simple使用Java

它應該是什麼樣子:

{"wallPosts": [ 
      {"userPosts0":[ 
       {"postText":"This is some post text"}, 
       {"postUser":"Atloids"}, 
       {"postDate":"03\/15\/1998"}, 
       {"postLikes":3} 
       ] 
      } 
      ] 
    } 

運行的代碼後的第一時間做些什麼:當跑了第二次

{"wallPosts": 
      {"userPosts0":[ 
       {"postText":"This is some post text"}, 
       {"postUser":"Atloids"}, 
       {"postDate":"03\/15\/1998"}, 
       {"postLikes":3} 
       ] 
      } 

    } 

錯誤代碼:螺紋

異常「 main「java.lang.ClassCastException:org.json.simple.JSONObject無法轉換爲org.json.simple.JSONArray at main.Data.main(Data.java:29)

的代碼:

try { 
     String JSON_FILE="/json/data.json"; 
     JSONParser parser = new JSONParser(); 
     FileReader fr = new FileReader(JSON_FILE); 

     System.out.println(1); 
     Object obj = parser.parse(fr); 

     System.out.println(2); 
     JSONObject jo = (JSONObject)obj; 
     System.out.println(jo); 


     System.out.println(3); 
     JSONArray wallPostsArray = (JSONArray) jo.get("wallPosts"); 
     System.out.println(wallPostsArray); 


     int numOfWallPosts = wallPostsArray.size(); 
     System.out.println("Number of Wall Posts: " + numOfWallPosts); 

     System.out.println(4); 
     JSONArray ja = new JSONArray(); 

     System.out.println(5); 
     JSONObject postText = new JSONObject(); 
     postText.put("postText", "This is some post text"); 
     JSONObject postUser = new JSONObject(); 
     postUser.put("postUser", "James Bond"); 
     JSONObject postData = new JSONObject(); 
     postData.put("postDate", "07/07/1997"); 
     JSONObject postLikes = new JSONObject(); 
     postLikes.put("postLikes", 3); 

     System.out.println(6); 
     ja.add(postText); 
     ja.add(postUser); 
     ja.add(postData); 
     ja.add(postLikes); 

     System.out.println(7); 
     JSONObject userPosts = new JSONObject(); 
     userPosts.put("userPosts"+numOfWallPosts++, ja); 


     wallPostsArray.add(userPosts); 
     System.out.println(userPosts); 

     jo.put("wallPosts", userPosts); 
     System.out.println(jo); 

     FileWriter file = new FileWriter(JSON_FILE); 

     file.write(jo.toJSONString()); 
     file.flush(); 
     file.close(); 

     System.out.println(wallPostsArray); 
    } 
    catch(ParseException e){ 
     System.out.println("No such file exists."); 
    } 
    catch(IOException io){ 
     System.out.println("No File."); 
    } 
} 

回答

0

你的對象是不同的 - 在所述第一代碼段「wallPosts」是對象(JSONArray),其中的一個陣列,並且在所述第二片段「w​​allPosts」只是一個JSON對象。

當你第二次運行它時,它的錯誤是因爲「wallPosts」不再是JSONArray。

+0

你會如何建議我第二次將「wallPosts」作爲JSONArray? –

+0

我的建議是將您的數據建模爲POJO。將文件讀入POJO,對對象進行更新,然後將對象寫回文件。 這是來自mykong的一個很好的小教程 - [如何將Java對象轉換爲/來自JSON(Jackson)](https://www.mkyong.com/java/how-to-convert-java-object-to-from -json-jackson) – StackTraceYo

+0

我不想走那條路。你對我目前的代碼有什麼建議嗎? –