java - 如何从 Java 中的 JSON 字符串中删除元素?
问题描述
我有一个 json 作为字符串,我需要使用 java 代码从中删除一个元素。感谢你的帮助。
例子。
尝试了数组和东西,但没有运气。
输入:需要删除图像
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
输出:
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
解决方案
下面是带有不同流行库的示例代码,以实现您想要的效果,如下所示:
杰克逊
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readValue(jsonStr, JsonNode.class);
((ObjectNode) node.get("widget")).remove("image");
System.out.println(node.toString());
格森
Gson gson = new Gson();
JsonElement jsonObj= gson.fromJson(jsonStr, JsonElement.class);
jsonObj.getAsJsonObject().get("widget").getAsJsonObject().remove("image");
System.out.println(jsonObj.toString());
抛弃
JSONObject jsonObj = new JSONObject(jsonStr);
jsonObj.getJSONObject("widget").remove("image");
System.out.println(jsonObj.toString());
推荐阅读
- git-diff - 如何找到两个文本文件之间的最大差异?
- tree - 为了确定图是否有奇循环,我们使用 BFS 还是 DFS?
- spring-boot - 如何为 spring-boot 配置 wait 和 maxAttempts 属性:从 Maven 命令行开始
- typescript - 在本机反应中获取和返回 Firestore 集合
- python - 仅从 JSON 对象动态获取给定键
- python - 如何在 FuncAnimation 中更改速度
- c - 从文件读取数据时出现分段错误
- angular - 公式生成器 - 具有自动完成和文本突出显示的文本区域
- python-3.x - 使用 mitmproxy 拦截 multipart/form-data 不起作用
- javascript - 在 JavaScript 中,如何在不遇到 ReferenceError 的情况下静态导入超类中的子类?