使用字典中的DataContract创建.NET对象

时间:2016-01-11 12:12:06

标签: c# datacontractserializer datacontract javascriptserializer

定义了一个类:

[DataContract]
public class Command
{
        [DataMember(Name = "cmdName")]
        public string CommandName { get; set; }

        [DataMember(Name = "cmdTransactionId")]
        public string CommandTransactionId { get; set; }
}

我想从字典中创建该类的实例:

Dictionary<string, object> propertyBag = new Dictionary<string, object>();
propertyBag["cmdName"] = "cmd1";
propertyBag["cmdTransactionId"] = "1";
Command command = deserializer.Create<Command>(propertyBag);

DataContractSerializer不适用于我,也不是JavaScriptSerializer.ConvertToType,因为他们每个人都错过了一件阻止我一次创建物品的作品。

2 个答案:

答案 0 :(得分:2)

JavaScriptSerializer可以在这里进行一些更改:

var propertyBag = new Dictionary<string, object>();
propertyBag["CommandName"] = "cmd1";
propertyBag["CommandTransactionId"] = "1";

var serializer = new JavaScriptSerializer();
var res = serializer.Serialize(propertyBag);

var command = serializer.Deserialize<Command>(res);

我使用Deserialize方法代替ConvertToType方法。第二个区别更为重要。我使用的字典包含与Command类中的属性名称相同的键。如果您不喜欢它,您应该尝试编写自定义JavaScriptConverter。请参阅此question

答案 1 :(得分:0)

也许您可以为deserializer.Create<Command>(propertyBag)尝试此代码:

public T Create<T>(IDictionary<string, object> propertyBag)
{
    var result = (T)FormatterServices.GetUninitializedObject(typeof(T));

    foreach (var item in from member in typeof(T).GetMembers()
                         let dataMemberAttr = member.GetCustomAttributes(typeof(DataMemberAttribute), true).Cast<DataMemberAttribute>().SingleOrDefault()
                         where dataMemberAttr != null && propertyBag.ContainsKey(dataMemberAttr.Name)
                         select new { Member = member, Value = propertyBag[dataMemberAttr.Name] })
    {
        var property = item.Member as PropertyInfo;
        if (property != null)
        {
            property.SetValue(result, item.Value, null);
            continue;
        }

        var field = item.Member as FieldInfo;
        if (field != null)
        {
            field.SetValue(result, item.Value);
            continue;
        }
    }

    return result;
}

此代码未经过测试 - 只需输入此处。