Skip to content

Gson – Remove Key from JSON example

Gson – Remove key from JSON example shows how to remove a key from JSON using the Gson library in Java. The example also shows how to remove a nested key from the JSON object.

How to remove a key value from JSON?

We can use the remove method of the JsonObject class to remove a key-value pair from the JSON.

The remove method removes the specified key from the JsonObject and returns the same.

Output

As we can see from the output, the department key and its value are removed from the JSON.

The above example removed the key that is located at the root level. How about the nested key? In that case, we first need to traverse to the object level and then use the remove method to remove the key. Consider the below given JSON.

If we want to remove the “years” property, we first need to traverse to the “position” object and then use the remove method as given below.

Output

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.