简体   繁体   English

如何从json中提取所有变量名?

[英]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.

相关问题 Java:如何从保存在路径中的多个文件夹中提取最大名称到文件夹名称都是数字的变量中? - Java: How to extract the largest name from multiple folders kept at a path into a variable where folder names are all numeric? 如何从此json字符串中获取所有名称 - how to fetch all names from this json string 我想使用ANTLR4从Java源文件中提取所有方法名称和变量名称 - I want to extract all method names and variable names from a java source file using ANTLR4 如何在Spring Boot中使用Java从JSON响应中提取特定部分,并更改JSON结构中的字段名称(如本例所示)? - How to extract a specific part from JSON response with changing fields names in JSON structure (as in this example) with Java in Spring Boot? Java - 如何从 JSON 架构中获取所有字段名称 - Java - How to get all the field names from JSON Schema 如何从JSON响应中获取所有属性名称(是否嵌套) - How to get all attributes names(nested or not) in from JSON response 如何从XSD提取标签名称? - How to extract tag names from an XSD? 如何从此JSON提取数据? - How to extract data from this JSON? 使用Eclipse JDT从变量声明中提取所有变量名 - Extracting all variable names from Variable declarations using Eclipse JDT 如何从JSON响应中提取ID并将其用作JMeter中另一个HTTP请求中的路径变量 - How to extract an ID from JSON response and use it as path variable in another HTTP requests in JMeter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM