Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an element from JSON string in Java?

Tags:

java

json

I have a json as a string and I need to remove one element from it using java code. Appreciate your help.

Example.

Tried arrays and stuff but no luck.

Input: Need to remove image

{"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;"
    }
}}   

Output:

{"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;"
    }
}}
like image 616
Abhijith Kolanakuduru Avatar asked Sep 07 '25 15:09

Abhijith Kolanakuduru


1 Answers

Here comes the sample code with different popular libraries to achieve what you want as follows:

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

Jettison

JSONObject jsonObj = new JSONObject(jsonStr);
jsonObj.getJSONObject("widget").remove("image");
System.out.println(jsonObj.toString());
like image 137
LHCHIN Avatar answered Sep 09 '25 04:09

LHCHIN