5

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).

Indrid
  • 962
  • 4
  • 25
  • 39
  • Possible duplicate of [Jsonpath with Jackson or Gson](https://stackoverflow.com/questions/34111276/jsonpath-with-jackson-or-gson) – jsalonen Aug 06 '17 at 09:19
  • 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). – Indrid Aug 06 '17 at 09:31
  • 1
    Then read it again. It contains an example, along with a link to the relevant documentation, showing how to use Jackson or Gson to parse and map the JSON. – JB Nizet Aug 06 '17 at 09:34
  • @JBNizet You are so kind. The other question contains an uncontested response stating that jsonpath is not supported in GSON then goes on to talk about Jayway. If there is a clear example of using GSON to perform jsonpath selections in that answer then it continues to elude me. – Indrid Aug 06 '17 at 09:41
  • 2
    If you want to use jsonpath selection, GSON is not what you're looking for. GSON is a JSON mapper. But JsonPath allows doing JsonPath selections. And it can use GSON to parse and map your JSON. – JB Nizet Aug 06 '17 at 09:54
  • Thanks for clarifying :-) Much appreciated. Looking into JayWay now... it could be the ideal solution. – Indrid Aug 06 '17 at 09:57

1 Answers1

4

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

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
DRG
  • 41
  • 3