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
?