简体   繁体   English

如何从JSON文件中删除项目?

[英]How to remove items from JSON files?

I'm new to JSON and GSON and as well as Java. 我是JSON和GSON以及Java的新手。 Currently I'm having difficulties on removing items in my Json files. 目前我在删除Json文件中的项目时遇到了困难。 Below are my code 以下是我的代码

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;

            }
        }
    }
}

and for my json's file structure 以及我的json的文件结构

{ "username": "admin", "password": "21232f297a57a5a743894a0e4a801fc3", "roles": "admin" }, { "username": "client", "password": "21232f297a57a5a743894a0e4a801fc3", "roles": "client" } {“username”:“admin”,“password”:“21232f297a57a5a743894a0e4a801fc3”,“roles”:“admin”},{“username”:“client”,“password”:“21232f297a57a5a743894a0e4a801fc3”,“roles”:“client” }

Thing I wanted it to happen: When I pressed deleteBtn, removeUser() will be executed and the users and the details will be removed. 我希望它发生:当我按下deleteBtn时,将执行removeUser()并删除用户和详细信息。

Thing that's happen: Nothing happen 事情发生了:没有任何事情发生

Can anyone guide me on how to do remove? 任何人都可以指导我如何删除?

sample code to read a jsonarray from a file , modify into a new array and store it back using apache-commons-io.jar 示例代码从文件中读取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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM