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

the*_*row 5 .net c# 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; }
}
Run Code Online (Sandbox Code Playgroud)

现在由于某种未知原因,DataContractJsonSerializer无法将JSON反序列化为字典(请参阅其他详细信息部分).
不幸的是,DataContractJsonSerializer也因为超出我的原因而被封存.
我需要一种方法来解决它,有没有人有线索?

jco*_*and 5

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

但是,对于大多数自定义序列化对象来说也是如此,所以希望这并不是什么大惊喜.

但是,现在它应该作为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"}]
Run Code Online (Sandbox Code Playgroud)

从javascript到JSON的相同关联:

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

{"Red":"Rosso","Blue":"Blu","Green":"Verde"}
Run Code Online (Sandbox Code Playgroud)

简而言之,这就是问题所在.


一些有用的后续链接

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