C# – Lookup nested field in ExpandoObject at runtime

say you have a JSON object like this

{
    home: {
        garage: {
            bike: {
                make: "honda"
            }
        }
    }
}

in C# you’ve loaded the JSON into an ExpandoObject like this:

dynamic json = JsonConvert.DeserializeObject("json text above...");

to lookup a field, you can just do

var make = json.home.garage.bike.make; // "honda"

which is just great.

but what if you need to lookup fields whose names you do not know at compile time?

with the little helper i wrote you can do this:

var fieldName = "home.garage.bike.make"; // this will be resolved at runtime

var make = json.GetField(fieldName);

==================

public static object GetField(this ExpandoObject expandoObject, string path)
{
    if (expandoObject == null)
        return null;

    var pathSegments = path.Split('.');
    var lastPathSegment = pathSegments[pathSegments.Length - 1];

    var cursor = (IDictionary)expandoObject;

    for (int i = 0; i < pathSegments.Length - 1; i++)
    {
        var pathSegment = pathSegments[i];

        cursor = (IDictionary)cursor[pathSegment];
    }

    object result = null;

    cursor.TryGetValue(lastPathSegment, out result);

    return result;
}

Cheers