简体   繁体   中英

Using JsonPath how can I get the inner value of these json objects

Say I have some json like this that I am parsing with JsonPath :

{
  A: {key: "1"}
  B: {key: "1"}
  C: {key: "1"}
  D: {key: "1"}
  E: {key: "1"}
}  

or

{
  A: {key: "7"}
  B: {key: "7"}
  E: {key: "7"}
  G: {key: "7"}
}  

A, B, C, D, E, ..., etc can be any tag and are not regularly named. However, key always has the same value in each of the objects. Using a JsonPath query how can I get the value of key ? To be clear, the input should be that json and the output should be a single string containing the value of key

One option is to use $..key . This will return a List of values.
Then we need to use 'Stream API` to get an element out of it.

List<?> result = JsonPath.parse(s1)
                      .read("$..key", List.class);

result.stream()
      .findAny()
      .ifPresent(System.out::println);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM