如何使用DataContractJsonSerializer反序列化一本字典? [英] How to deserialize a dictionary using DataContractJsonSerializer?
问题描述
我有以下型号:
[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无法反序列化到JSON字典(见其他详细信息部分)。
不幸的是DataContractJsonSerializer也被密封的原因,是超越我。
我需要一种方法来解决它,没有人得到线索?
Now for some unknown reason, DataContractJsonSerializer can't deserialize JSON into a dictionary (See additional details section).
Unfortunately DataContractJsonSerializer is also sealed for reasons that are beyond me.
I need a way to get around it, does anyone got a clue?
推荐答案
由于没有一本字典类的JavaScript它很难有JSON deparse为一体。什么你将要做的就是自己写一个转换器。
Since there isn't a dictionary type in javascript it's rather difficult to have JSON deparse into one. What you're going to have to do is write a converter yourself.
不过,这也是大多数自定义序列化对象真实的,所以希望这没有什么好大的惊喜。
However, that's also true on most custom serialization objects, so hopefully that comes as no big surprise.
现在它应该,但是,阅读作为一个KeyValuePair,所以你可以尝试,看看它是否至少反序列化给你。相反,你需要一个名单,其中,KeyValuePair&LT;&GT;&GT;
Now it should, however, read in as a KeyValuePair so you can try that, to see if it's at least deserializing for you. Rather, you would need a List<KeyValuePair<>>
什么词典&LT;字符串,字符串&GT;
转换成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:
The same associative from javascript into JSON:
var a = {};
a["Red"] = "Rosso";
a["Blue"] = "Blu";
a["Green"] = "Verde";
{"Red":"Rosso","Blue":"Blu","Green":"Verde"}
所以这是概括地说这个问题。
So there's the problem in a nutshell.
一些后续环节的有效性
<一个href="http://my6solutions.com/post/2009/06/17/The-serialization-and-deserialization-of-the-generic-Dictionary-via-the-DataContractJsonSerializer.aspx">http://my6solutions.com/post/2009/06/17/The-serialization-and-deserialization-of-the-generic-Dictionary-via-the-DataContractJsonSerializer.aspx
<一个href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.collectiondatacontractattribute.aspx">http://msdn.microsoft.com/en-us/library/system.runtime.serialization.collectiondatacontractattribute.aspx
这篇关于如何使用DataContractJsonSerializer反序列化一本字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!