简体   繁体   中英

How to serialize a derived class in Silverlight

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM