Skip to content

Instantly share code, notes, and snippets.

@dmitry-osin
Created July 22, 2020 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmitry-osin/d9eae17866bf84a67a392f167000fdee to your computer and use it in GitHub Desktop.
Save dmitry-osin/d9eae17866bf84a67a392f167000fdee to your computer and use it in GitHub Desktop.
@UtilityClass
public class XPathUtils {
public Map<String, Object> extractValue(@NonNull String json, @NonNull String xPath) {
Map<String, Object> jsonValue = U.fromXmlMap(json);
return extractValue(jsonValue, xPath);
}
@SuppressWarnings("unchecked")
public Map<String, Object> extractValue(@NonNull Map<String, Object> jsonMap, @NonNull String xPath) {
Map<String, Object> sourceMap = optimizeMapForXPath(jsonMap);
JXPathContext context = JXPathContext.newContext(sourceMap);
return (Map<String, Object>)context.getValue(xPath);
}
private Map<String, Object> optimizeMapForXPath(Map<String, Object> jsonMap) {
Map<String, Object> destination = new LinkedHashMap<>();
for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof List) {
List<LinkedHashMap<String, Object>> sourceMap = (List<LinkedHashMap<String, Object>>) value;
Map<String, Object> resultMap = new LinkedHashMap<>();
for (int i = 0; i < sourceMap.size(); i++) {
LinkedHashMap<String, Object> map = sourceMap.get(i);
resultMap.put(key + i, map);
}
destination.put(key, optimizeMapForXPath(resultMap));
}
else if (value instanceof String) {
destination.put(key, value);
} else if (value instanceof Map) {
Map<String, Object> resultMap = (Map<String, Object>) value;
destination.put(key, optimizeMapForXPath(resultMap));
} else {
throw new IllegalArgumentException(String.valueOf(value));
}
}
return destination;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment