How To Retrieve Nested Object Value In .NET

Problem Statement

We have a nested object. We would like a function where you pass in the object and a key and get back the value.

Example Inputs

Input object = {“a”:{“b”:{“c”:”d”}}}
Input key = a/b/c
Output value = d
Input object = {“x”:{“y”:{“z”:”a”}}}
Input key = x/y
Output value = {“z”:”a”}

Proposed Solution

To achieve this, we can split the key by "/" and check each level of the object. JObject class from the Newtonsoft.Json Nuget package can be used to parse and navigate a JSON object.

How To Retrieve Nested Object Value In .NET

This function takes a JObject and a key, splits the key by '/' character, iterate over the keys array and on each iteration, it uses the key to get the value at that key, until it reaches the last key. The value at the last key will be returned and if the key not found, it will return key does not exist.

Source Code

using Newtonsoft.Json.Linq;
using System;
using System.Reflection;
namespace GetNestedValueByKey {
    class Program {
        static void Main(string[] args) {
            static object GetNestedValueByKey(JObject obj, string key) {
                var keys = key.Split('/');
                JToken current = obj;
                foreach(var k in keys) {
                    current = current[k];
                    if (current == null) return $ "Key {key} not exists";
                }
                return current;
            }
            /*Tests*/
            JObject obj = JObject.Parse("{\"a\":{\"b\":{\"c\":\"d\"}}}");
            var value = GetNestedValueByKey(obj, "a/b/c");
            Console.WriteLine(value); // Output: "d"
            obj = JObject.Parse("{\"x\":{\"y\":{\"z\":\"a\"}}}");
            value = GetNestedValueByKey(obj, "x/y");
            Console.WriteLine(value); // Output: { "z": "a" }
            obj = JObject.Parse("{\"x\":{\"y\":{\"z\":\"a\"}}}");
            value = GetNestedValueByKey(obj, "x");
            Console.WriteLine(value); // Output: { "y": { "z": "a" } }
            obj = JObject.Parse("{\"x\":{\"y\":{\"z\":\"a\"}}}");
            value = GetNestedValueByKey(obj, "k"); // key not exists in json
            Console.WriteLine(value); // Output: Key k not exists
        }
    }
}

Output

Next Recommended Reading Nested Interfaces in C#.NET