How to serialize a derived class in Silverlight

不打扰是莪最后的温柔 提交于 2020-02-04 07:23:18

问题


I created a custom control in XAML, and added some custom properties as well. Now, I want to serialize it to JSON if possible. Here is (essentially) what I have:

public partial class MyCustomClass : UserControl
{
    public Dictionary<char, int[]> ValueMap;
    public int Value { get; set; }
}

And in the code that handles serialization:

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();
    }
}

However, serializer.WriteObject(ms, objectToSerialize); throws

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."

Now, when I do add those attributes to the MyCustomClass, I of course get the same exception, only this time for System.Windows.UIElement instead of MyCustomClass.

So, is there a way to serialize my custom derived class with the existing serialization method, or should I just write a custom serialization methods for MyCustomClass?


回答1:


I think you are better off implementing IXmlSerializable here, as you really don't want to indiscriminately serialize everything in the base class (and I don't believe you can, quite frankly).

Rather, implement IXmlSerializable on MyCustomClass, and then the DataContractJsonSerializer will be able to use that implementation to serialize to/from JSON.



来源:https://stackoverflow.com/questions/513215/how-to-serialize-a-derived-class-in-silverlight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!