Created
July 22, 2020 16:38
-
-
Save dmitry-osin/d9eae17866bf84a67a392f167000fdee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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