在Java中使用GSON如何获取JSON对象的所有键?

WBOY
WBOY 转载
2023-08-30 23:45:06 269浏览

在Java中使用GSON如何获取JSON对象的所有键?

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.*;
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());
      }
   }
}

输出

Raja
Ravi
Chaitanya
Adithya

以上就是在Java中使用GSON如何获取JSON对象的所有键?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除