Check if a field exists in JsonObject using gson in java

45 Views Asked by At

I have a following JSON structure

{
  "entity": {
    "bsid": "8452",
    "name": "Name limited",
    "contact": "CONTACT",
    "imgurl": "http://testlocalhost.com/",
  },
  "doc": {
    "details": {
      "bsid": "8452",
      "type": "pdf"
    }
    "name": "estimates",
  }
}

I need to find if bsid is present in the JSON structure. An important point to note is that the structure may change. However, what is guaranteed is bsid field will be present somewhere in the structure which I need to find and if present, get its value(8452 in this case. The value will be same everywhere it's present)

Since I am using google gson library, I know this can be achieved with the following statement:

jsonObject.getAsJsonObject("entity").get("bsid")

Here jsonObject is actually JsonObject of google gson which holds the above structure

However, as I mentioned the structure may change and bsid may not be present directly under entity. Hence I need a way to find a field in the structure globally.

1

There are 1 best solutions below

2
Herbert Marshall On

Just need to walk the json and find the value.

@Test
void jsonTest() {
    String json = """
{
    "entity": {
        "name": "Name limited",
        "contact": "CONTACT",
        "imgurl": "http://testlocalhost.com/"
    },
    "doc": {
        "details": {
            "type": "pdf",
            "test": [
                "bar",
                { "testing": "ok" },
                {
                    "foo": false,
                    "bsid": "12345"
                }
            ]
        },
        "name": "estimates"
    }
}
""";
    findValue(
        JsonParser.parseString( json ).getAsJsonObject(),
        "bsid"
    )
        .findAny()
        .ifPresentOrElse(
            System.out::println,
            () -> System.out.println( "Empty" )
        );

}

private Stream<String> findValue( JsonElement json, String field ) {
    if ( json.isJsonArray() )
        return StreamSupport.stream( json.getAsJsonArray().spliterator(), false )
            .flatMap( element -> findValue( element, field ) );
    if ( ! json.isJsonObject() ) return Stream.empty();
    return json.getAsJsonObject()
        .entrySet()
        .stream()
        .flatMap( entry -> field.equals( entry.getKey() ) ?
            Stream.of( entry.getValue().getAsJsonPrimitive().getAsString() ) :
            findValue( entry.getValue(), field  )
        );
}