如何在JAVA中从JSON文件中删除元素
我有一个JSON文件,我想读取它,遍历它的元素,然后在所有对象中删除一个特定的elementUserID 这是我的Json文件:如何在JAVA中从JSON文件中删除元素,java,json,Java,Json,我有一个JSON文件,我想读取它,遍历它的元素,然后在所有对象中删除一个特定的elementUserID 这是我的Json文件: [ { "UserID": 1, "UserName": "rooter", "Password": "12345", "Country": "UK", "Email": "sac@gmail.com" }, { "UserID": 2, "UserName": "binu", "Passwo
[
{
"UserID": 1,
"UserName": "rooter",
"Password": "12345",
"Country": "UK",
"Email": "sac@gmail.com"
},
{
"UserID": 2,
"UserName": "binu",
"Password": "123",
"Country": "uk",
"Email": "Binu@gmail.com"
},
{
"UserID": 3,
"UserName": "cal",
"Password": "123",
"Country": "uk",
"Email": "cal@gmail.com"
},
{
"UserID": 4,
"UserName": "nera",
"Password": "1234",
"Country": "uk",
"Email": "nera@gmail.com"
}
]
我还使用org.json.simple库读取文件,解析其元素并删除其中一个元素,下面是我使用的代码:
public static void main(String[] args) throws Exception {
JSONParser jsonparser = new JSONParser();
try( FileReader reader = new FileReader("test.json"))
{
Object obj = jsonparser.parse(reader);
ObjectMapper mapper = new ObjectMapper();
JSONArray List = (JSONArray) obj;
JsonNode root = mapper.readTree(reader);
for (JsonNode jsonNode : root) {
if (jsonNode instanceof ObjectNode) {
ObjectNode o = (ObjectNode) jsonNode;
o.remove("UserID");
}
}
System.out.println(List);
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
问题是,当我解析元素时,它会删除元素,但在文件中不会更改,但是我想将其从文件中删除并保存回去,您知道怎么做吗。如果JSONArray列表包含您编辑的JSON,您应该能够使用.toJSONString从中获取JSON字符串,然后使用如下文件编写器将其写入您的文件:
try {
fw = new FileWriter("test.json");
fw.write(list.toJSONString());
} catch (IOException e) {
e.printStackTrace();
} finally {
fw.close();
}
请检查以下代码,这些代码将帮助您解决问题:
public static void main(String[] args) throws Exception {
JSONParser jsonparser = new JSONParser();
try( FileReader reader = new FileReader("test.json"))
{
Object obj = jsonparser.parse(reader);
JSONArray list = (JSONArray) obj;
list.forEach(node->{
((JSONObject) node).remove("UserID");
});
System.out.println(list);
saveAsJsonFile(list.toJSONString(),"test.json");
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
private static void saveAsJsonFile(String seasonData, String fileName) {
try (final FileOutputStream outputStreamSeason = new FileOutputStream(fileName)) {//fileName is absolute path of file (dir + filename)
outputStreamSeason.write(seasonData.getBytes());
System.out.println(fileName + " file save successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
现在要做的是删除元素并打印新的json。您必须将新的json保存回文件中。在删除所有用户ID后,将数组写回文件中。您可以使用try with resources或至少在finally块中移动close作为良好做法。