使用点表示法将对象转换为字典

时间:2016-05-03 13:34:09

标签: c# dictionary

请找到问题的附件小提琴Link

我想要做的是将对象转换为字典 该对象看起来像这样

var person = new Person
{
    FirstName = "Jon",
    LastName = "Doe",
    Address = new Address
    {
        Street = "Melkbos",
        PostalCode = 90210
    }
};   

所需的输出应该如下所示

{
 {"FirstName", "Jon"},
 {"LastName", "Doe"},
 {"Address.Street", "Melkbos"},
 {"Address.PostalCode", 90210},
};

因此,如果对象是嵌套的,我想要一个点符号

2 个答案:

答案 0 :(得分:3)

您需要对要序列化的属性类型使用递归和测试。我使用IsSerializable修改了部分代码来执行此操作。您可能需要调整它以满足您的确切需求:

public static IDictionary<string, T> ToDictionary<T>(this object source)
{
    if (source == null)
        ThrowExceptionWhenSourceArgumentIsNull();

    var dictionary = new Dictionary<string, T>();
    AddPropertiesToDictionary(new List<string>(), source, dictionary);
    return dictionary;
}

private static void AddPropertiesToDictionary<T>(IList<string> path, object source, IDictionary<string, T> dictionary)
{
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
    {
        var value = property.GetValue(source);
        if (IsOfType<T>(value))
        {
            if (property.PropertyType.IsSerializable) {
                dictionary.Add((path.Any() ? string.Join(".", path) + "." : "") + property.Name, (T)value);
            }
            else
            {
                path.Add(property.Name);
                AddPropertiesToDictionary(path, value, dictionary);
            }
        }
    }
}

输出结果为:

Key                Value
FirstName          Jon  
LastName           Doe  
Address.Street     Melkbos 
Address.PostalCode 90210

你应该可以修改它,很容易在那里得到花括号和引号。

答案 1 :(得分:0)

我认为没有必要进行反射,因为你知道属性名称,你可以试试这个:

namespace personToDictionary
{
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Address Address { get; set; }

        public Dictionary<string, string> ToDictionary()
        {
            return new Dictionary<string, string>
            {
                {"FirstName", FirstName},
                {"LastName", LastName},
                {"Address.Street", Address.Street},
                {"Adress.PostalCode", Address.PostalCode.ToString()}
            };
        } 
    }

    public class Address
    {
        public string Street { get; set; }
        public int PostalCode { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person
            {
                FirstName = "Jon",
                LastName = "Doe",
                Address = new Address
                {
                    Street = "Melkbos",
                    PostalCode = 90210
                }
            };
            var personDictionary = person.ToDictionary();
        }
    }
}

希望有所帮助