Home > Java > javaTutorial > body text

How to get all keys of a JSON object using GSON in Java?

WBOY
Release: 2023-08-30 23:45:06
forward
688 people have browsed it

How to get all keys of a JSON object using GSON in Java?

A Gson is a library that can be used to parse Java objects to JSON and vice-versa. It can also be used to convert a JSON string to an equivalent Java object. In order to parse java object to JSON or JSON to java object, we need to import com.google.gson package in the Java program.

We can get all the keys of a JSON object in the below example

Example

import java.util.*;
import com.google.gson.*;<strong>
</strong>import org.json.*;
public class GetJSONAllKeysTest {
   public static void main(String[] args) {
      String jsonStr = "{\"Raja\":\"Java\", \"Ravi\":\"SAP\", \"Chaitanya\":\"Python\", \"Adithya\":\"Spark\"}";
      JsonParser parser = new JsonParser();
      JsonElement element = parser.parse(jsonStr);
      JsonObject obj = element.getAsJsonObject();
      Set<Map.Entry<String, JsonElement>> entries = obj.entrySet();
      for(Map.Entry<String, JsonElement> entry: entries) {
         System.out.println(entry.getKey());
      }
   }
}
Copy after login

输出

Raja
Ravi
Chaitanya
Adithya
Copy after login

The above is the detailed content of How to get all keys of a JSON object using GSON in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!