如何在GSON中使用jsonpath

use*_*399 5 java json jsonpath gson

我正在掌握 JAVA 的 GSON,并且有一个关于如何从我正在使用的大型 json 文档中进行类似 jsonpath 的选择的问题。

例如,使用如下 json 文档:

{
  "environment": {
    "red": {
      "area": {
        "1": {
          "name": "foo"
        },
        "2": {
          "name": "bar"
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

jsonpath 表达式:

   $.environment.red.area
Run Code Online (Sandbox Code Playgroud)

返回:

 [
  {
    "1": {
      "name": "foo"
    },
    "2": {
      "name": "bar"
    }
  }
]
Run Code Online (Sandbox Code Playgroud)

在GSON中如何实现这种选择呢?

我不清楚该问题被标记为重复的问题的答案。似乎说它可以在 GSON 中完成,但没有说明或显示如何完成(据我所知)。

小智 4

您可以使用下面的代码..

public static String getJsonStringForPath(String strJson, String strJPath)
    {
        Configuration JACKSON_JSON_NODE_CONFIGURATION = Configuration.builder().jsonProvider(new GsonJsonProvider())
                .options(Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS).build();

        Configuration conf = Configuration.builder().jsonProvider(new GsonJsonProvider())
                .options(Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS).build();

        JsonArray objArrJ = JsonPath.using(conf).parse(strJson).read(strJPath);     
        String strRetJson = ""+objArrJ;
        return strRetJson;
    }

//Pass the param of  JsonPath : "$.environment[*].red"
Run Code Online (Sandbox Code Playgroud)

请参阅 jsonpath 的文档:https: //github.com/json-path/JsonPath