我在 XAML 中创建了一个自定义控件,并添加了一些自定义属性。现在,如果可能的话,我想将其序列化为 JSON。这是(基本上)我所拥有的:
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
:
Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required."
现在,当我将这些属性添加到 MyCustomClass
时,我当然会得到相同的异常,只是这次是针对 System.Windows.UIElement
而不是 >MyCustomClass
.
那么,有没有办法使用现有的序列化方法序列化我的自定义派生类,或者我应该为 MyCustomClass
编写自定义序列化方法?
最佳答案
我认为你最好在这里实现 IXmlSerialized,因为你真的不想不加区别地序列化基类中的所有内容(坦率地说,我不相信你可以)。
相反,在 MyCustomClass 上实现 IXmlSerializable,然后 DataContractJsonSerializer 将能够使用该实现来序列化到 JSON 或从 JSON 进行序列化。
关于c# - 如何在 Silverlight 中序列化派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/513215/