0

Hi I need to build a utility which will take input in the form of key like this: source.payload.header.version It should return version 1.1.1 from the the sample json below

"source":{
  "payload":{
    "Header":{
            "version":"1.1.1"

I am new to json and json-simple

nikhil udgirkar
  • 367
  • 1
  • 7
  • 23
  • Are you willing to use a library for this? Because the easiest path would be to take a library like gson or org.json and let them handel this. – Florian Hergenhahn May 13 '20 at 10:24
  • I found JSON-SIMPLE okay. I am not pretty sure about other libraries. Will check out gson. But can you help me with JSON-SIMPLE – nikhil udgirkar May 13 '20 at 10:30
  • This kind of utility already exists and you can use it - https://github.com/json-path/JsonPath (unless of course you are developing this for fun/learning) – Smile May 13 '20 at 11:07

1 Answers1

0

I could not find a native implementation in the library you wanted to use, which can handel this kind of request. So I came up with my own little code snippet which might help you.

private static Object getNestedValue(final String path, JSONObject obj) {
    String currentKey;
    String currentPath = path;

    while (true) {
        // Get current key with tailing '.'
        currentKey = currentPath.substring(0, currentPath.indexOf('.') + 1);
        // Remove the current key from current path with '.'
        currentPath = currentPath.replace(currentKey, "");
        // Remove the '.' from the current key
        currentKey = currentKey.replace(".", "");

        // Check if the current key is available
        if (obj.containsKey(currentKey))
            obj = (JSONObject) obj.get(currentKey);     // This can cause an Class Cast exception, handel with care
        else if (currentKey.isEmpty())                  // Check if the currentKey is empty
            return obj.get(currentPath);                // Return the result
        else
            return null;
    }
}