Reputation: 83
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;"
}
}}
Upvotes: 4
Views: 10019
Reputation: 4009
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());
Upvotes: 5
Reputation: 573
Install and import this package:
import org.json.*;
And using the following code:
try {
String src = "{\"widget\": {\n"
+ " \"debug\": \"on\",\n"
+ " \"window\": {\n"
+ " \"title\": \"Sample Konfabulator Widget\",\n"
+ " \"name\": \"main_window\",\n"
+ " \"width\": 500,\n"
+ " \"height\": 500\n"
+ " },\n"
+ " \"image\": { \n"
+ " \"src\": \"Images/Sun.png\",\n"
+ " \"name\": \"sun1\",\n"
+ " \"hOffset\": 250,\n"
+ " \"vOffset\": 250,\n"
+ " \"alignment\": \"center\"\n"
+ " },\n"
+ " \"text\": {\n"
+ " \"data\": \"Click Here\",\n"
+ " \"size\": 36,\n"
+ " \"style\": \"bold\",\n"
+ " \"name\": \"text1\",\n"
+ " \"hOffset\": 250,\n"
+ " \"vOffset\": 100,\n"
+ " \"alignment\": \"center\",\n"
+ " \"onMouseUp\": \"sun1.opacity = (sun1.opacity / 100) * 90;\"\n"
+ " }\n"
+ "}} ";
JSONObject obj = new JSONObject(src);
obj.getJSONObject("widget").remove("image");
System.out.println("obj: " + obj);
} catch (JSONException ex) {
ex.printStackTrace();
}
Hope this will help you guy.
Upvotes: 0