How to use jsonpath in GSON

Viewed 10260

I'm getting to grips with GSON for JAVA and have a question about how to make jsonpath like selections from the large json documents I'm working with.

For example with a json document like:

{
  "environment": {
    "red": {
      "area": {
        "1": {
          "name": "foo"
        },
        "2": {
          "name": "bar"
        }
      }
    }
  }
}

The jsonpath expression of:

   $.environment.red.area

Returns:

 [
  {
    "1": {
      "name": "foo"
    },
    "2": {
      "name": "bar"
    }
  }
]

How can this selection be achieved in GSON?

The answer given to the question for which this question is flagged as a duplicate is not clear to me. It seems to say that it CAN be done in GSON but does not say or show how (as far as I can tell).

1 Answers

You may use the code below..

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"

Refer to documentation: of jsonpath : https://github.com/json-path/JsonPath

Related