Вы можете прочитать пути и значения отдельно, а затем собрать результаты вместе.
Вот пример использования Jayway JsonPath :
String json = "[\n" +
" {\n" +
" \"id\": 1,\n" +
" \"person\": {\n" +
" \"name\": \"john\",\n" +
" \"age\": \"28\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"id\": 2,\n" +
" \"person\": {\n" +
" \"name\": \"jane\",\n" +
" \"age\": \"25\"\n" +
" }\n" +
" }\n" +
"]";
Object parse = Configuration.defaultConfiguration()
.jsonProvider()
.parse(json);
JsonPath path = JsonPath.compile("$[*].person.name");
// read the paths
JSONArray asPaths = path.read(parse, Configuration.builder()
.options(Option.AS_PATH_LIST).build());
String[] paths = asPaths.toArray(new String[asPaths.size()]);
// read the values
JSONArray asValues = path.read(parse);
String[] values = asValues.toArray(new String[asValues.size()]);
// put the paths and values together using the array indexes
Map<String, String> valuesAndPaths = new HashMap<>();
for (int i = 0; i < values.length; i++) {
valuesAndPaths.put(values[i], paths[i]);
}
for (Map.Entry<String, String> entry : valuesAndPaths.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
Это распечатает:
john, $[0]['person']['name']
jane, $[1]['person']['name']