-1
目的:JSONArrayデータを外部の.jsonファイルの既存のJSONArrayに追加します。JSONを使用してJSONを適切に.jsonファイルにフォーマットすることはできません。
それは何のようになります。それは、コードを最初に実行した後に何
{"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}
]
}
}
エラーコード第二時間走った: "スレッドで
例外をメイン "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.");
}
}
2回目に「wallPosts」をJSONArrayとして保持する方法を教えてください。 –
私の提案はあなたのデータをPOJOとしてモデル化することです。ファイルをPOJOに読み込んでオブジェクトに更新し、オブジェクトをファイルに書き戻します。 ここにmykongからのちょっとしたチュートリアルです - [JSON(Jackson)へのJavaオブジェクトの変換方法](https://www.mkyong.com/java/how-to-convert-java-object-to-from -json-jackson) – StackTraceYo
私はそのルートに行きたくありません。私の現在のコードについて何か提案がありますか? –