gpt4 book ai didi

java - 如何从 Java 中的 JSON 字符串中删除元素?

转载 作者:行者123 更新时间:2023-12-01 23:58:07 25 4
gpt4 key购买 nike

我有一个 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;"
}
}}

最佳答案

这里是使用不同流行库来实现您想要的示例代码,如下所示:

jackson

ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readValue(jsonStr, JsonNode.class);
((ObjectNode) node.get("widget")).remove("image");
System.out.println(node.toString());

Gson

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());

关于java - 如何从 Java 中的 JSON 字符串中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58194380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com