简体   繁体   English

使用 json-simple (JAVA) 删除 JSON 文件的部分

[英]Remove Section of a JSON File with json-simple (JAVA)

Hello I want to delete an section of a JSON File in Java with JSON-Simple.您好,我想使用 JSON-Simple 删除 Java 中 JSON 文件的一部分。

The JSON File JSON 文件

{
        "MYID": {
            "user": "name",
            "task": "aufgabe",
            "status": "true"
        },
        "MYID2": {
            "user": "name2",
            "task": "aufgabe2",
            "status": "false"
        },
        "MYID3": {
            "user": "name3",
            "task": "aufgabe3",
            "status": "true"
        }
}

I want to delete the complete "MYID" section.我想删除完整的“MYID”部分。 I already tried jsonObject.remove("MYID");我已经尝试过jsonObject.remove("MYID"); but it don't worked.但它不起作用。

Try:尝试:

jsonObj.getAsJsonObject("").remove("MYID");

This approach requires a String argument.这种方法需要一个字符串参数。 First try to print the jsonObject (jsonObect.toString()) or debug it.首先尝试打印jsonObject (jsonObect.toString())或调试它。 That should be a Map with another inner Maps and see the structure of such object to remove the part you are interested in.那应该是带有另一个内部地图的 Map 并查看此类 object 的结构以删除您感兴趣的部分。

I successfully removed element with this code:我使用以下代码成功删除了元素:

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

class SimpleJson {
    public static void main(String[] args) throws IOException {
        JSONObject jObject = (JSONObject) JSONValue.parse(json);
        jObject.remove("MYID3");
        System.out.println(jObject);
        try (FileWriter writer = new FileWriter(new File("/path/result2.json"))) {
            jObject.writeJSONString(writer);
        }

        // java 11 
        // Files.writeString(Path.of("/path/dir1", "result.json"), jObject.toJSONString());
    }
    ...
}

Dependency: com.googlecode.json-simple json-simple 1.1.1依赖: com.googlecode.json-simple json-simple 1.1.1

Output : Output

{
  "MYID": {
    "task": "aufgabe",
    "user": "name",
    "status": "true"
  },
  "MYID2": {
    "task": "aufgabe2",
    "user": "name2",
    "status": "false"
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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