将对象序列化为扁平的Dictionary <string,string> </string,string>

时间:2012-07-24 23:44:35

标签: c# .net asp.net-mvc serialization

给出一个班级

public class MyClass
{
    public MyInnerClass Property1 {get;set;}
    public MyInnerClass2 Field1
    public MyInnnerClass[] Property2 {get;set;}
}

我需要一个序列化程序,与MVC序列化程序不同,将上面的序列化为以下字典。

new {
        {
            "Property1.InnerField", "1",
        },
        {
            "Field1.InnerProperty", "7/7/2007"
        },
        {
            "Property2[0].InnerProperty", "0"
        },
        {
            "Property2[1].InnerProperty", "1"
        }
}

基本上它需要位置和原生值,或进一步递归,直到找到非引用类型。

1 个答案:

答案 0 :(得分:3)

谈到你的问题,我们可能会以简洁的方式提出答案,并排除任何现有的序列化架构。这样你就可以完全自由地走进对象引用树而不用使用Reflection并填充结果字典。

我们需要一个简单的方法来访问给定的对象,然后为每个公共属性递归调用自身。签名应该包含一个字符串,表示当前的父链(例如:"Property1.InnerProperty4.InnerProperty7"),返回类型应该是Dictionary<string,string>,只有来自当前和嵌套对象的东西。 在开始时它应该检查参数是否是值类型,并且在前一种情况下只需创建一个新字典,添加一个新的KeyValuePair(父+名称,值)并返回;而在后一种情况下,创建一个新的Dictionary,然后foreach公共属性调用本身传递当前属性,父+ name字符串,并将返回的字典与先前创建的字典连接,并在循环结束时返回这个大字典。我们可以在开始时添加另一个条件,检查传递的对象是否实现了IEnumerable接口之类的东西。在这种情况下,而不是仅仅循环遍历其成员,循环遍历其索引器并为每个项目调用方法。

我有时间实施我昨天所描述的内容。这里有一个递归方法,用于返回给定对象的(公共属性全名) - (值)对的字典。当然,你可能不会详细地了解你想要达到的目标,但你会发现很多技巧,想法和概念来构建你自己的:

namespace MyNamespace
{
    public class ClassA {
        int p1 = 1;
        string p2 = "abcdef"; 
        List<string> p3 = new List<string>() { "ghi","lmn" };
        ClassB p4 = new ClassB();
        ClassB p5 = null;

        public int PA1 { get { return p1; } }
        public string PA2 { get { return p2; } }
        public List<string> PA3 { get { return p3; } }
        public ClassB PA4 { get { return p4; } }
        public ClassB PA5 { get { return p5; } }
    }

    public class ClassB{
        private string p1 = "zeta";
        public string PB1 { get { return p1; } }
    }

    public class Program {

        public void Main()
        {
            ClassA o = new ClassA();
            Dictionary<string, string> result = GetPropertiesDeepRecursive(o, "[o]", new List<string>() { "MyNamespace" });
        }

        /// <summary>
        /// Returns a dictionary of propertyFullname-value pairs of the given object (and deep recursively for its public properties)
        /// note: it's object oriented (on purpose) and NOT type oriented! so it will just return values of not null object trees
        /// <param name="includedNamespaces">a list of full namespaces for whose types you want to deep search in the tree</param>
        /// </summary>        
        public Dictionary<string, string> GetPropertiesDeepRecursive(object o, string memberChain, List<string> includedNamespaces)
        {

            List<string> types_to_exclude_by_design = new List<string>() { "System.string", "System.String" };

            //the results bag
            Dictionary<string, string> r = new Dictionary<string, string>();

            //if o is null just return value = [null]
            if (o == null)
            {
                r.Add(memberChain, "[null]");
                return r;
            }

            //the current object argument type
            Type type = o.GetType();

            //reserve a special treatment for specific types by design (like string -that's a list of chars and you don't want to iterate on its items)
            if (types_to_exclude_by_design.Contains(type.FullName))
            {
                r.Add(memberChain, o.ToString());
                return r;
            }

            //if the type implements the IEnumerable interface...
            bool isEnumerable =
                type
                .GetInterfaces()
                .Any(t => t == typeof(System.Collections.IEnumerable));
            if (isEnumerable)
            {
                int i_item = 0;
                //loop through the collection using the enumerator strategy and collect all items in the result bag
                //note: if the collection is empty it will not return anything about its existence,
                //      because the method is supposed to catch value items not the list itself                
                foreach (object item in (System.Collections.IEnumerable)o)
                {
                    string itemInnerMember = string.Format("{0}[{1}]", memberChain, i_item++);
                    r = r.Concat(GetPropertiesDeepRecursive(item, itemInnerMember, includedNamespaces)).ToDictionary(e => e.Key, e => e.Value);
                }
                return r;
            }

            //here you need a strategy to exclude types you don't want to inspect deeper like int,string and so on
            //in those cases the method will just return the value using the specific object.ToString() implementation
            //now we are using a condition to include some specific types on deeper inspection and exclude all the rest
            if (!includedNamespaces.Contains(type.Namespace))
            {
                r.Add(memberChain, o.ToString());
                return r;
            }

            //otherwise go deeper in the object tree...            
            //and foreach object public property collect each value
            PropertyInfo[] pList = type.GetProperties();
            foreach (PropertyInfo p in pList)
            {
                object innerObject = p.GetValue(o, null);
                string innerMember = string.Format("{0}.{1}", memberChain, p.Name);
                r = r.Concat(GetPropertiesDeepRecursive(innerObject, innerMember, includedNamespaces)).ToDictionary(e => e.Key, e => e.Value);
            }
            return r;
        }
    }
}