Asp.Net将Dictionary <string,object =“”>反序列化为对象</string,>

时间:2010-09-23 20:31:50

标签: c# asp.net serialization

反序列化

的最佳方式是什么?
Dictionary<string, object>{
   {"fName", "John"},
   {"lName", "Doe"},
   {"email", "john@doe.net"}
}

到这个

class Member{
   string fName;
   string lName;
   string email;
}

6 个答案:

答案 0 :(得分:2)

这不是通常意义上的序列化,通常是指获取一些磁盘或网络格式的数据(二进制,ASCII,JSON等)并将其加载到运行时对象中。

但是,如果我理解正确,我认为你要做的是......

public Member( Dictionary<string,object> dictionary )
{ 
    fName = dictionary["fName"];
    lName = dictionary["lName"];
    email = dictionary["email"];
}

// usage Member m = new Member( inputDictionary );

答案 1 :(得分:2)

如果结构是静态的:

return new Member 
{
   fName = myDictionary["fName"], 
   lName = myDictionary["lName"], 
   email = myDictionary["email"]
};

如果在设计时不知道结构:

public static T Hydrate<T>(this Dictionary<string, string> theDictionary, 
   T myObject = new T()) where T:new() //default/optional parameter is valid in 4.0 only
{

   //var myObject = myObject ?? new T(); //alternative in 3.5 and previous

   foreach(string key in myDictionary.Keys)
   {
      var propInfo = typeof(T).GetProperty(key);

      if(propInfo == null) throw new ArgumentException("key does not exist");
      propInfo.SetValue(myObject, theDictionary[key], null);
   }
   return myObject;
}

答案 2 :(得分:1)

现在,NewtonSoft在ASP.NET应用程序中变得非常普遍,如果我需要这种类型的映射的简短而甜蜜的解决方案,我可以使用这样的代码。当然,如果第三方图书馆尚未出现,可能会引起滥用,但有时我们会使用有效的图书馆。和牛顿软件一样!

using Newtonsoft.Json;
class SerializationTests
{
    public void DictionarySerializeSample()
    {

        var dict = new Dictionary<string, object>
        {
            {"fName", "John"},
            {"lName", "Doe"},
            {"email", "john@doe.net"}
        };

        string dictInJson = JsonConvert.SerializeObject(dict);
        var member = JsonConvert.DeserializeObject<Member>(dictInJson);

        // use Newtonsoft to write out the object re-serialized
        Console.WriteLine(JsonConvert.SerializeObject(member, Formatting.Indented));

    }

    public class Member
    {
        public string fName;
        public string lName;
        public string email;
    }
}

答案 3 :(得分:0)

一种似乎有意义的方法是为此设置静态辅助函数。

public static Member Create(Dictionary<string, object inputs)
{
    Member oNew = new Member();
    oNew.fName = inputs["fName"].ToString();
    // etc
    return oNew;
}

答案 4 :(得分:0)

你也可以使用反射,它可能是很多代码,取决于你实际使用的对象,但它会更灵活。这可能不是一个完整的样本,但它可以让你了解一般。

public T InstantiateFromDictionary<T>(Dictionary<string, object> values) where T : new()
{
   Type t = typeof(T);
   T instance = new T();
   foreach(KeyValuePair<string, object> kvp in values)
   {
        PropertyInfo prop = t.GetProperty(kvp.Key);
        prop.SetValue(instance, kvp.Value, null);
   }

   return instance;
}

答案 5 :(得分:0)

这不是序列化,而是转换。如果你真的想要它可以转换,那么让它可以转换。 Implement TypeConverter

示例代码

using System;

使用System.Collections.Generic; 使用System.Linq; 使用System.Text; 使用System.IO; 使用System.Xml.Linq; 使用System.Diagnostics; 使用System.Xml.Serialization; 使用System.ComponentModel; 使用System.Globalization;

命名空间ConsoleApplication1 {

internal class MemberConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context,
  Type sourceType)
    {
        if (sourceType == typeof(Dictionary<string, object>))
        {
            return true;
        }
        return base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context,
  CultureInfo culture, object value)
    {
        if (value is Dictionary<string, object>)
        {
            Member member = new Member();
            Dictionary<string, object> d = (Dictionary<string, object>)value;
            if (d.ContainsKey("fName")) { member.fName = Convert.ToString(d["fName"]); };
            if (d.ContainsKey("lName")) { member.lName = Convert.ToString(d["lName"]); };
            if (d.ContainsKey("email")) { member.email = Convert.ToString(d["email"]); };
            return member;
        }
        return base.ConvertFrom(context, culture, value);
    }

    public override object ConvertTo(ITypeDescriptorContext context,
  CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(Dictionary<string, object>))
        {
            Member member = (Member)value;
            Dictionary<string, object> d = new Dictionary<string, object>();
            d.Add("fName", member.fName);
            d.Add("lName", member.lName);
            d.Add("email", member.email);
            return d;
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }

}

[TypeConverter(typeof(MemberConverter))]
internal class Member
{
    public string fName;
    public string lName;
    public string email;
}

class Program
{
    static void Main(string[] args)
    {
        var d = new Dictionary<string, object> {
           {"fName", "John"},
           {"lName", "Doe"},
           {"email", "john@doe.net"}
        };

        Member m = (Member)TypeDescriptor.GetConverter(typeof(Member)).ConvertFrom(d);

        Debugger.Break();
    }
}

}