0

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?

Jara G
  • 33
  • 5
  • you can map your json to a map, and then extract keySet from it. – Ankur Dec 20 '19 at 11:52
  • Does this answer your question? [Map an array of JSON objects to a java.util.Map and vice versa](https://stackoverflow.com/questions/33914460/map-an-array-of-json-objects-to-a-java-util-map-and-vice-versa) – miljon Dec 20 '19 at 11:53

3 Answers3

1

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.

Rômulo M. Farias
  • 1,483
  • 1
  • 15
  • 29
1

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

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.

Christian S.
  • 877
  • 2
  • 9
  • 20