c# - 如何在 Silverlight 中序列化派生类

标签 c# .net silverlight json serialization

我在 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/

相关文章:

javascript - 如何让 Google map 在 Visual Studio Web 表单中工作?

C# 比较两个对象值

c# - 报表查看器字体仅在 WIndows 服务器计算机上变长

c# - ReactiveUI 和 Caliburn Micro 在一起?

Silverlight 3 - PRISM - 使用 WCF 检索和加载模块定义 - 可能吗?

Silverlight:通过 XAML 设置 DateTime 属性?

c# - 从 DataTable 填充时如何禁用 DataGridView 图像列中的空图像

c# - 在 C# 中实现 Photoshop 滤镜

c# - 从三个非唯一的 List<T> 中获取一个唯一的 List<T>

.NET:线程开销