代码之家  ›  专栏  ›  技术社区  ›  the_drow

如何使用DataContractJsonSerializer反序列化词典?

  •  5
  • the_drow  · 技术社区  · 14 年前

    我有以下型号:

    [DataContract]
    public class MessageHeader
    {
        private Guid? messageId;
    
        public Guid MessageId
        {
            get
            {
                if (messageId == null)
                    messageId = Guid.NewGuid();
    
                return messageId.Value;
            }
        }
    
        [DataMember]
        public string ObjectName { get; set; }
    
        [DataMember]
        public Dictionary<string, object> Parameters { get; set; } // Can't deserialize this
    
        [DataMember]
        public Action Action { get; set; }
    
        [DataMember]
        public User InitiatingUser { get; set; }
    }
    

    不知为什么, DataContractJsonSerializer can't deserialize JSON into a dictionary (见附加细节部分)。
    不幸的是,DataContractJsonSerializer也因为我无法理解的原因而被密封。
    我需要一个办法绕过它,有人知道吗?

    1 回复  |  直到 14 年前
        1
  •  5
  •   jcolebrand    14 年前

    由于javascript中没有字典类型,因此很难将JSON分解为一个字典类型。你要做的就是自己写一个转换器。

    不过,这在大多数自定义序列化对象上也是正确的,所以希望这不会让人大吃一惊。

    不过,现在它应该作为KeyValuePair读入,这样您就可以尝试这样做,看看它是否至少对您进行了反序列化。相反,你需要一个 List<KeyValuePair<>>

    多棒的 Dictionary<string,string> 转换为for JSON:

    var dict = new Dictionary<string,string>; 
    dict["Red"] = "Rosso"; 
    dict["Blue"] = "Blu"; 
    dict["Green"] = "Verde";
    
    [{"Key":"Red","Value":"Rosso"},
     {"Key":"Blue","Value":"Blu"},
     {"Key":"Green","Value":"Verde"}]
    

    从javascript到JSON的相同关联:

    var a = {}; 
    a["Red"] = "Rosso"; 
    a["Blue"] = "Blu"; 
    a["Green"] = "Verde";
    
    {"Red":"Rosso","Blue":"Blu","Green":"Verde"}
    

    所以简单来说就是问题所在。


    一些有用的后续链接

    http://my6solutions.com/post/2009/06/17/The-serialization-and-deserialization-of-the-generic-Dictionary-via-the-DataContractJsonSerializer.aspx

    http://msdn.microsoft.com/en-us/library/system.runtime.serialization.collectiondatacontractattribute.aspx