简体   繁体   中英

How to extract all variable names from json?

I need an array of variable names from JSON. For example, if I receive

{
  "Java": 20526,
  "Shell": 292,
  "Groovy": 213
}

I want to map it to

String[] {"Java", "Shell", "Groovy"}

How can I do that effectively? Can I use Jackson?

You can use Jackson to parse to an HashMap<String, Object> and then get the keys of your HashMap (if you intend to get all keys of the first level of course).

To get keys from all levels, you can create a recusive function which when the value of the key is another HashMap you extract it again.

Convert json to map and get the keys. Below is the code. I have used GSON library.

String json = "{\"Java\": 20526,\"Shell\": 292,\"Groovy\": 213}";
Map map = new Gson().fromJson(json, new TypeToken<Map<String, Integer>>() {
        }.getType());
System.out.println(map.keySet());

One-liner using Gson 2.8.6:

String json = "{\"Java\":20526,\"Shell\":292,\"Groovy\":213}";
String[] keys = JsonParser.parseString(json).getAsJsonObject().keySet().toArray(new String[0]);

Parse the JSON string to a JsonObject , get the key set and convert it to an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM