-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathJsonUtil.java
More file actions
51 lines (44 loc) · 1.58 KB
/
JsonUtil.java
File metadata and controls
51 lines (44 loc) · 1.58 KB
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
51
package io.beanmapper.spring.util;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Utilities for working with JSON.
*
* @author Jeroen van Schagen
* @since Nov 13, 2015
*/
public class JsonUtil {
/**
* Retrieve the property names mentioned in a JSON content.
*
* @param json the JSON content
* @param objectMapper the object mapper
* @return set of the property names
*/
public static Set<String> getPropertyNamesFromJson(String json, ObjectMapper objectMapper) {
try {
JsonNode tree = objectMapper.readTree(json);
return getPropertyNames(tree, "");
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not retrieve property names from JSON.", e);
}
}
private static Set<String> getPropertyNames(JsonNode node, String base) {
Set<String> propertyNames = new HashSet<>();
Iterator<String> iterator = node.fieldNames();
while (iterator.hasNext()) {
String fieldName = iterator.next();
String propertyName = isEmpty(base) ? fieldName : base + "." + fieldName;
propertyNames.add(propertyName);
propertyNames.addAll(getPropertyNames(node.get(fieldName), propertyName));
}
return propertyNames;
}
private static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
}