Skip to content

Gson – How to Update JSON Value

Gson – How to update JSON value example shows how to update a value for a JSON key using the Gson library in Java. The example also shows how to update value using JsonObject without converting JSON to POJO.

How to modify JSON value?

Many times we want to update or modify the value for a specific JSON key. The Gson library provides methods for doing exactly that. To update the value of a specific key, we can use the addProperty method of the JsonObject class.

The addProperty method adds the provided key and value to the JsonObject. What the Gson JavaDoc does not say is that it replaces the value if the key already exists! So we can utilize this method to modify the value.

For this example, I am going to use the below given JSON.

Let’s update/modify the department of this employee JSON.

Output

As we can see from the output, the department key is updated with the new value HR.

The addProperty method is overloaded to accept String, Number, Boolean, and Character data types as the new value.

We can also the modify department value from a string to a JSON array, but in this case, we need to use the add method instead of the addProperty method.

The add method accepts a JsonElement object as a value, so we can put an array or an object using this method.

Output

As we can see from the output, the department key now has an array as a value instead of a string.

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

About the author

Leave a Reply

Your email address will not be published.