
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get All Keys of a JSON Object Using Gson in Java
JSON is the data interchange format that stores values in key-value pairs. (To learn more about JSON, you can refer to the JSON tutorial). So, as we have key and value in JSON, we will try to get all those keys using the Gson library.
Gson Library: Retrieving all the keys of a JSON
Gson is a third-party Java library developed by Google. It is used for converting Java objects to JSON and vice versa. To know more about Gson, refer to the Gson tutorial.
We can use the keySet() method of JsonObject class to get all the keys of a JSON object. The keySet()
method returns a set of keys present in the JSON object.
We cannot use the Gson library without downloading or adding it to the project. Because it is not a part of the Java standard library. But we can still use the Gson library without downloading it. We can use it from the Maven repository.
Let's see how to add Gson library to our project:
Adding Gson to your Project
First, we need to add the Gson library to our project. If you are using Maven, add this to your pom.xml
file:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.9</version> </dependency>
If you don't use Maven, add a jar file to your project. You can download the jar file from here.
Steps to Retrieve all Keys
Steps to get all the keys of a JSON object using Gson library:
- First, import the Gson library, as discussed above.
- Then create a JSON object.
- Then we will create an instance of Gson class.
- Next, we will get all the keys of the JSON object using the keySet() method.
- Finally, we will print the keys.
Example
Following is the code to get all the keys of a JSON object using the Gson library:
import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.util.Set; import java.util.Iterator; import java.util.Map.Entry; public class GetAllKeysOfJsonObject { public static void main(String[] args) { // Create a JSON object String jsonString = "{"name":"Ansh", "age":23, "city":"New York"}"; JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject(); // Get all the keys of the JSON object Set<String> keys = jsonObject.keySet(); // Print the keys System.out.println("Keys in the JSON object:"); for (String key : keys) { System.out.println(key); } } }
Following is the output of the above code:
Keys in the JSON object: name age city