我在XAML中創建了自定義控件,並添加了一些自定義屬性。現在,如果可能,我想將其序列化爲JSON。這裏是(本質)我有:如何序列化Silverlight中的派生類
public partial class MyCustomClass : UserControl
{
public Dictionary<char, int[]> ValueMap;
public int Value { get; set; }
}
而且在處理序列化的代碼:
public static string Serialize(object objectToSerialize)
{
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(objectToSerialize.GetType());
serializer.WriteObject(ms, objectToSerialize);
ms.Position = 0;
using (StreamReader reader = new StreamReader(ms))
return reader.ReadToEnd();
}
}
然而,serializer.WriteObject(ms, objectToSerialize);
拋出
System.Runtime.Serialization.InvalidDataContractException
:
它標記與 DataContractAttribute屬性和 標誌着其所有成員的你想 系列化與 DataMemberAttribute屬性。 或者,你可以確保 類型是公共的,有一個無參數 構造 - 的 所有公共成員,那麼該類型將被序列化,並 沒有任何屬性將被要求」
現在,當我做這些屬性添加到MyCustomClass
,我當然會得到相同的例外,只是這一次爲System.Windows.UIElement
,而不是MyCustomClass
。
那麼,有沒有一種方法來序列與現有序列化方法我的自定義派生類,或者我應該只需編寫一個自定義的序列化方法ds代表MyCustomClass
?
哇,我決不會預計將IXmlSerializable的一個DataContractJsonSerializer工作,但它的作用。我想到的第一件事就是ISerializable的,但顯然它不是在Silverlight的支持。 – 2009-02-05 05:25:32