GSON | Extract JSON's Root Name | JsonPath Or JsonPointer

204 views Asked by At

I am looking at extracting the root element of a JSON document. It looks like this is possible neither using JsonPointer nor JsonPath as my attempts to look up for such an expression has been unsuccessful. Any tips would be appreciated. TIA.

Sample document:

{
    "MESSAGE1_ROOT_INPUT": {
        "CTRL_SEG": "test"
    }
}

The below using gson 2.9.0:

$.*~

produces:

{"CTRL_SEG": "test"}

while JSONPath Online produces this:

[
  "MESSAGE1_ROOT_INPUT"
]

The attempt is to get text "MESSAGE1_ROOT_INPUT" using JsonPath/JsonPointer expression(s). Note that, extracting this the traditional (substring or regex on a stringified json text) way, would preferably be my last resort.

Background: We are building an API service that accepts JSON documents with different roots. Such as, MESSAGE2_ROOT_INPUT, MESSAGE3_ROOT_INPUT, etc. It is based on this, the routing of a message further will occur.

Supported/Employed Languages: Java/GSON Library/RegEx

1

There are 1 answers

0
Marcono1234 On

Gson does not natively support JSONPath or JSON Pointer. However, you can quite efficiently obtain the name of the first property using JsonReader:

public static String getFirstPropertyName(Reader reader) throws IOException {
    // Don't have to call JsonReader.close(); that would just close the provided reader
    JsonReader jsonReader = new JsonReader(reader);
    jsonReader.beginObject();
    return jsonReader.nextName();
}

There are however two things to keep in mind:

  • This only reads the beginning of the JSON document; it neither verifies that the complete JSON document has valid syntax, nor checks if there might be more top-level properties
  • This consumes some data from the Reader; to further process the data you have to buffer the data to allow re-reading it again (you can also first store the JSON in a String and pass a StringReader to JsonReader)