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

时间:2010-11-16 21:46:06

标签: c# .net json deserialization

我有以下型号:

[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 个答案:

答案 0 :(得分:5)

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

然而,在大多数自定义序列化对象上也是如此,所以希望这并不是什么大惊喜。

现在它应该作为KeyValuePair读入,所以你可以尝试,看看它是否至少为你反序列化。相反,您需要List<KeyValuePair<>>

Dictionary<string,string>转化为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