Java 如何通过键值更新JSONObject?
我有这个JSONFileJava 如何通过键值更新JSONObject?,java,json,Java,Json,我有这个JSONFile {"PostsDetails":[ { "pageInfo": { "pagePic": "http://example.com/abc.jpg", "pageName": "abc" }, "id": 1, "posts": [ { "likesCount": "2", "nameOfPersonWhoPosted": "Jane Doe", "post_id": "098
{"PostsDetails":[
{
"pageInfo": {
"pagePic": "http://example.com/abc.jpg",
"pageName": "abc"
},
"id": 1,
"posts": [
{
"likesCount": "2",
"nameOfPersonWhoPosted": "Jane Doe",
"post_id": "0987654321_123456789012",
"timeOfPost": "0987654321",
"actor_id": "0987654321",
"message": "Can't wait to see it!",
"picOfPersonWhoPosted": "http://example.com/abc.jpg"
}
]
}
]}
我有这个方法可以通过id更新并将JSONObject写入文件。如何按id更新对象?我不知道该怎么做。我试图从文件中删除旧对象,然后将新对象放入文件中,但我不希望将其附加到文件的最后一部分
参数上的“JSONObject post”具有对象的更新值
public Message updatePost(long id, JSONObject post) {
Message message = new Message("Failed", false);
if (!post.isEmpty()) {
try{
JSONObject jsonObject = fileUtil2.getFileJSONObject();
JSONArray arr = (JSONArray) jsonObject.get("PostsDetails");
Iterator itr = arr.iterator();
while (itr.hasNext()) {
JSONObject obj = (JSONObject) itr.next();
if (obj.get("id").equals(id)) {
//Not sure what to put here
}
if(fileUtil2.writeToFile(jsonObject)){
message.setMessage("Contact Updated.");
message.setStatus(true);
}
else{
message.setMessage("An error occured.");
message.setStatus(false);
}
}
}
catch(Exception e){
}
}
return message;
}
要使用JSon作为持久性格式,您必须使用的不仅仅是文件系统。看看MongoDb或其他面向文档的数据库(主要是nosql)@Aubin它是我的学校作业,他们要求我们使用文件系统。如果您必须只使用一个文件,您应该加载整个文件,将其拆分为按id索引的文档(使用映射),用Map.put(id,post)替换条目,然后重写整个文件。