Search code examples
c#datacontractserializerdatacontractjavascriptserializer

Create .NET object with DataContract from a dictionary


Having a class defined:

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

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

I would like to create an instance of that class from a dictionary:

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

DataContractSerializer is not working for me nor is the JavaScriptSerializer.ConvertToType as each of them is missing a piece that stop s me from creating objects in one go.


Solution

  • JavaScriptSerializer will work here with some changes:

    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);
    

    I used Deserialize method instead of ConvertToType one. The second difference is more significant. A dictionary used by me contains keys which are the same as names of properties in Command class. If you don't like it you should try to write a custom JavaScriptConverter. See this question.