首页 > 解决方案 > 如何从 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;"
    }
}}

标签: javajson

解决方案


下面是带有不同流行库的示例代码,以实现您想要的效果,如下所示:

杰克逊

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

推荐阅读