[英]How to extract all variable names from json?
I need an array of variable names from JSON.我需要一个来自 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).您可以使用
Jackson
解析为HashMap<String, Object>
,然后获取 HashMap 的键(当然,如果您打算获取第一级的所有键)。
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.要从所有级别获取键,您可以创建一个递归函数,当键的值是另一个
HashMap
您再次提取它。
Convert json to map and get the keys.将 json 转换为 map 并获取密钥。 Below is the code.
下面是代码。 I have used GSON library.
我使用过 GSON 库。
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:使用 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.将 JSON 字符串解析为
JsonObject
,获取键集并将其转换为数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.