获取Json字符串的所有key

需求:根据所给出的json字符串提取他的所有节点的key

1
2
3
4
5
6
7
8
9
10
"data":{
"fullJudgement":{
"id":"69dcd1b5-a443-46d3-80d6-60d10d90f41a",
"court":{
"id":"3398",
"name":"青铜峡市人民法院",
"type":"court"
}
}
}

比如上面其中一个key为data.court.name

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
private static List<String> parseAsObject(String prefix, JsonObject root) {
String newPrefix = StringUtils.isEmpty(prefix) ? "" : prefix + ".";
List<String> result = new LinkedList<>();
for (Map.Entry<String, JsonElement> element : root.entrySet()) {
String name = newPrefix + element.getKey();
JsonElement value = element.getValue();
if (value.isJsonPrimitive()) {
result.add(name);
} else if (value.isJsonArray()) {
result.addAll(parseAsArray(name, value.getAsJsonArray()));
} else if (value.isJsonObject()) {
result.addAll(parseAsObject(name, value.getAsJsonObject()));
}
}
return result;
}

private static List<String> parseAsArray(String prefix, JsonArray array) {
List<String> result = new LinkedList<>();
int i = 0;
for (JsonElement ele : array) {
// String name = prefix + "[" + (i++) + "]";
String name = prefix;
if (ele.isJsonObject()) {
result.addAll(parseAsObject(name, ele.getAsJsonObject()));
}
}
return result;
}

// 测试
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
// Json字符串省略
String contentJson = "";
JsonElement root = new JsonParser().parse(contentJson);
List<String> result = parseAsObject("", root.getAsJsonObject());
for (String s : result) {
if (map.containsKey(s)) {
map.put(s, map.get(s) + 1);
} else {
map.put(s, 1);
}
}
result.stream().forEach(System.out::println);
}
1
2
3
4
5
<dependency>      
<groupId>com.google.code.gson</groupId> 
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
赏个🍗吧
0%