[英]How to remove items from JSON files?
我是JSON和GSON以及Java的新手。 目前我在删除Json文件中的项目时遇到了困难。 以下是我的代码
public void removeUser() throws IOException{
File accounts = new File("accounts.json");
delete(accounts);
}
void delete(File acc) throws IOException {
if (acc.exists()) {
List userlist = new ArrayList();
Iterator<Users> iterator = userlist.iterator();
while (iterator.hasNext()) {
if (iterator.next().getUsername().equals(deleteTxt.getText())) {
iterator.remove();
notifications();
deleteTxt.setText(null);
notificationLbl.setText("Wish granted!");
break;
}
}
}
}
以及我的json的文件结构
{“username”:“admin”,“password”:“21232f297a57a5a743894a0e4a801fc3”,“roles”:“admin”},{“username”:“client”,“password”:“21232f297a57a5a743894a0e4a801fc3”,“roles”:“client” }
我希望它发生:当我按下deleteBtn时,将执行removeUser()并删除用户和详细信息。
事情发生了:没有任何事情发生
任何人都可以指导我如何删除?
示例代码从文件中读取jsonarray,修改为新数组并使用apache-commons-io.jar将其存储回来
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public static void delete(String username) throws JSONException, IOException {
File file = new File("E:\\accounts.json");
String encoding = Charset.defaultCharset().toString();
JSONArray oldDataArray = new JSONArray(FileUtils.readFileToString(file, encoding));
System.out.println(oldDataArray);
JSONArray newDataArray = new JSONArray();
for(int n=0;n<oldDataArray.length();n++) {
JSONObject nthObject = oldDataArray.getJSONObject(n);
if(!username.equals(oldDataArray.getJSONObject(n).get("username"))) {
newDataArray.put(nthObject);
}
}
System.out.println(newDataArray);
FileUtils.writeStringToFile(file, newDataArray.toString(), encoding);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.