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.
1 2 3 4 5 6 7 |
{ "Id": "EMP001", "Name": "Bob", "Age": 22, "IsManager": false, "ReservedParking": null } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.javacodeexamples.gsonexamples; import java.util.Set; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class GsonGetAllKeysExample { public static void main(String[] args) { String jsonData = "{\"Id\": \"EMP001\",\"Name\": \"Bob\",\"Age\": 22,\"IsManager\": false,\"ReservedParking\": null}"; //parse and get the JsonObject JsonObject jsonObject = JsonParser.parseString(jsonData).getAsJsonObject(); //get all the keys from the JsonObject Set<String> setKeys = jsonObject.keySet(); //iterate the JSON keys for(String key : setKeys) { System.out.println(key); } } } |
Output
1 2 3 4 5 |
Id Name Age IsManager ReservedParking |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.javacodeexamples.gsonexamples; import java.util.Map.Entry; import java.util.Set; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class GsonGetAllKeysExample { public static void main(String[] args) { String jsonData = "{\"Id\": \"EMP001\",\"Name\": \"Bob\",\"Age\": 22,\"IsManager\": false,\"ReservedParking\": null}"; //parse and get the JsonObject JsonObject jsonObject = JsonParser.parseString(jsonData).getAsJsonObject(); //get all entries from the JsonObject Set<Entry<String, JsonElement>> entries = jsonObject.entrySet(); //iterate the entries to get all key-value pairs for(Entry<String, JsonElement> entry : entries) { System.out.println(entry.getKey() + " => " + entry.getValue()); } } } |
Output
1 2 3 4 5 |
Id => "EMP001" Name => "Bob" Age => 22 IsManager => false ReservedParking => null |
Please let me know your views in the comments section below.