我有JSON的下面片:與DataContractJsonSerializer反序列化問題
[{
"name": "numToRetrieve",
"value": "3",
"label": "Number of items to retrieve:",
"items": {
"1": "1",
"3": "3",
"5": "5"
},
"rules": {
"range": "1-2"
}
},
{
"name": "showFoo",
"value": "on",
"label": "Show foo?"
},
{
"name": "title",
"value": "Foo",
"label": "Foo:"
}]
所有在同一行版本(適合字符串文字):
[{\"name\":\"numToRetrieve\",\"value\":\"3\",\"label\":\"Number of items to retrieve:\",\"items\":{\"1\":\"1\",\"3\":\"3\",\"5\":\"5\"},\"rules\":{\"range\":\"1-2\"}},{\"name\":\"showFoo\",\"value\":\"on\",\"label\":\"Show foo?\"},{\"name\":\"title\",\"value\":\"Foo\",\"label\":\"Foo:\"}]
在上述例子中,name
,value
和label
是必需的,但items
和rules
是可選的。
這裏是我試圖反序列化到類:
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace foofoo
{
[DataContract]
public sealed class FooDef
{
[DataMember(Name = "name", IsRequired = true)]
public string Name { get; set; }
[DataMember(Name = "value", IsRequired = true)]
public string Value { get; set; }
[DataMember(Name = "label", IsRequired = true)]
public string Label { get; set; }
[DataMember(Name = "items", IsRequired = false)]
public Dictionary<string, string> Items { get; set; }
[DataMember(Name = "rules", IsRequired = false)]
public Dictionary<string, string> Rules { get; set; }
}
}
下面是我用反序列化代碼:
var json = new DataContractJsonSerializer(typeof(List<FooDef>));
var bar = "[{\"name\":\"numToRetrieve\",\"value\":\"3\",\"label\":\"Number of items to retrieve:\",\"items\":{\"1\":\"1\",\"3\":\"3\",\"5\":\"5\"},\"rules\":{\"range\":\"1-2\"}},{\"name\":\"showFoo\",\"value\":\"on\",\"label\":\"Show foo?\"},{\"name\":\"title\",\"value\":\"Foo\",\"label\":\"Foo:\"}]";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(bar));
var foo = json.ReadObject(stream);
stream.Close();
一切進展相當不錯,除了items
和rules
是空的首先通過FooDef
。我已經嘗試了所有在陽光下試圖讓他們填充的東西:定製類,NameValueCollection
,KeyValuePair<string, string>
,List
這兩個後者,以及其他所有似乎適用的集合。 [編輯:我忘了嘗試Hashtable
,這似乎是一個明顯的候選人。沒有工作。]
問題,因爲我認爲它是items
和rules
下的關鍵部分是開放式的。也就是說,它並不總是被稱爲range
或3
。任何建議或想法?
這是我所擔心的。由於反對,我避免切換到JavaScriptSerializer,但我很高興聽到它在3.5 SP1中不贊成。我會用這個班級來嘗試。 – bbrown 2009-03-02 03:48:20