obj to dic props

 avatar
unknown
plain_text
2 years ago
764 B
1
Indexable
public static Dictionary<string, object> ObjectToDictionary(object obj)
{
    var dict = new Dictionary<string, object>();
    var properties = obj.GetType().GetProperties();
    foreach (var property in properties)
    {
        var value = property.GetValue(obj);
        if (value == null)
        {
            dict.Add(property.Name, null);
        }
        else if (value.GetType().IsPrimitive || value is string)
        {
            dict.Add(property.Name, value);
        }
        else
        {
            var nestedDict = ObjectToDictionary(value);
            foreach (var kvp in nestedDict)
            {
                dict.Add($"{property.Name}.{kvp.Key}", kvp.Value);
            }
        }
    }
    return dict;
}