2
我有兩個代碼段解析字典
代碼1
string json = @"{""properties"":{""name"":""carl""}}";
try
{
MemoryStream stream = GetMemoryStreamFromString(json);
Type type = typeof(Person);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
object obj = serializer.ReadObject(stream);
Debug.WriteLine(obj);
Person person = obj as Person;
}
catch (Exception ee)
{
Debug.WriteLine(ee.Message);
}
//And my classes
[DataContract]
public class Person
{
[DataMember]
public Property properties { set; get; }
public Person() { }
}
[DataContract]
public class Property
{
[DataMember]
public string name { set; get; }
public Property() { }
}
代碼2
string json = @"{""properties"":{""name"":""carl""}}";
try
{
MemoryStream stream = GetMemoryStreamFromString(json);
Type type = typeof(Person);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
object obj = serializer.ReadObject(stream);
Debug.WriteLine(obj);
Person person = obj as Person;
}
catch (Exception ee)
{
Debug.WriteLine(ee.Message);
}
//And my class
[DataContract]
public class Person
{
[DataMember]
public Dictionary<string,string> properties { set; get; }
public Person() { }
}
代碼1工作正常,但代碼2給我例外。這裏是日誌
數據協定類型'ScrollViewExample.Person'不能被反序列化,因爲成員'屬性'不公開。公開成員將修復此錯誤。或者,您可以將其設置爲內部,並在程序集中使用InternalsVisibleToAttribute屬性,以啓用內部成員的序列化 - 請參閱文檔以獲取更多詳細信息。請注意,這樣做有一定的安全隱患。
這裏的問題是,我沒有一個爲properties
定義的結構,它可以有任何鍵,所以我不能爲它定義一個類。我發佈這個問題,因爲我有一個problem和調查後,我發現我無法解析字典。所以我制定我的問題轉化爲簡單的一個,這樣你們可以給你的輸入
您是否考慮使用http://json.codeplex.com/而不是框架的序列化程序? – weismat 2013-04-04 07:23:14
不,我不使用它作爲'DataContractJsonSerializer'適用於windows-8,我只是將我的代碼移植到wp8 – 2013-04-04 07:28:01