Skip to content

Gson – Get All Keys from JSON Object

Gson – Get all keys from JSON Object example shows how to get all the key names contained in a JSON object using the Gson library in Java. The example also shows how to get all key-value pairs from the JSON object.

We are going to use the below given JSON for this example.

How to get all key names from JSON?

To get all keys from the JSON object, we can use the keySet method of the JsonObject class. This method returns a Set view of all the property keys contained in the JSON.

Output

How to get all keys and values from JSON?

We can get a JSON property value by specifying a key. But in many cases, the keys are not predetermined, which means the keys can be dynamic. In such cases, we can get all the keys stored in the JSON object and iterate them one by one to get the values.

First of all, we need to parse the JSON to get the object of the JsonObject class. Once we get that, we can use the entrySet method to get the Set object of all the JSON property-value entries. We can then iterate the set of entries to get the keys and values.

Here is an example that gets all the keys and values from the JSON object.

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.