0

How to serialize a c# class if can't mark base class as Serializable.

I am using Caliburn Micro in c# wpf application and MyViewModel is derived from Screen (https://caliburnmicro.com/documentation/composition). I need to serialize (Xml serializer / BinarySerializer / DataContractSerializer) object of MyViewModel in a file so that I can use it later.

I can mark MyViewModel as [Serializable] but getting exception that base class (which is Screen from caliburn micro) is not marked as [Serializable] so can't serialize object. I can't add attribute as [Serializable] in Screen because its a third party library.

Can anyone suggest me how to serialize MyViewModel object ?

[Serializable]
public class MyViewModel : Screen
{
  // Rest of functionalities
}

I am getting the exception : Type 'Caliburn.Micro.Screen' in Assembly 'Caliburn.Micro, Version=3.2.0.0, Culture=neutral, PublicKeyToken=1f2ed21f' is not marked as serializable.

Arvind Pandey
  • 141
  • 1
  • 8
  • 2
    Are you limited to using the built-in .NET serializers? There are plenty of third party serializers out there such as JSON.NET which don't require a [Serializable] attribute. – ekolis Aug 08 '19 at 15:28
  • 1
    In a typical MVVM application you would serialize the Model rather than the ViewModel. – RogerN Aug 08 '19 at 15:34
  • I used NewtonSoft Json for JsonSerialization but getting blank string. Example : https://www.newtonsoft.com/json/help/html/SerializingJSON.htm – Arvind Pandey Aug 08 '19 at 20:39

1 Answers1

0

Below links helped to solve my problem

DataContractSerializer: How to serialize classes/members without DataContract/DataMember attributes

Why do I need a parameterless constructor?

Pseudo Code: Serialization:

using (var stream = File.Open(filePath, FileMode.Create))
            {
                var writer = new DataContractSerializer(myViewModelObject.GetType());
                writer.WriteObject(stream, myViewModelObject);
                stream.Close();
            }

Deserialization:

using (var fs = new FileStream(filePath, FileMode.Open))
            {
                var reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                var deserializer = new DataContractSerializer(MyViewModel);
                var deserializedType = deserializer.ReadObject(reader, true);
                reader.Close();
                fs.Close();
                return deserializedType;
            }
Arvind Pandey
  • 141
  • 1
  • 8