Skip to content

Gson get value by key example

Gson get value by key example shows how to get JSON value by key using the Gson library. We can directly get value by specifying the key using JsonObject or we can get value using the POJO class.

1. Using JsonObject

This approach converts the string JSON data to JsonObject using the fromJson method. Once we get the JsonObject, we can specify the key in the get method to get the corresponding value from it.

The get method returns a JsonElement object. We need to use the getAsXXX method to get the value from it. For example, for an int value, we need to use the getAsInt method.

This method returns the entry as a primitive int value.

Here is an example of that.


Make sure to use the respective getAsXXX method for the data type of the value.

2. Using the Pojo class

Instead of parsing JSON data in the JsonObject object, we can directly convert the data to a Pojo class. In this case, we need to use the getter method corresponding to the key to access its value.


In this approach, we need to make sure to define the Pojo fields with the correct data types. Notice that in the above example, the salary key has a value without double quotes in the string JSON data and it also contains a decimal point number. Hence, in the Emp class, I’ve defined the salary field as double.

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

About the author

Leave a Reply

Your email address will not be published.