Jara G
Jara G

Reputation: 33

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?

Upvotes: 0

Views: 878

Answers (3)

Christian S.
Christian S.

Reputation: 982

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.

Upvotes: 0

Ramamohan Reddy
Ramamohan Reddy

Reputation: 11

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());

Upvotes: 1

R&#244;mulo M. Farias
R&#244;mulo M. Farias

Reputation: 1523

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.

Upvotes: 1

Related Questions