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.

3
  • 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. Commented Aug 8, 2019 at 15:28
  • 1
    In a typical MVVM application you would serialize the Model rather than the ViewModel. Commented Aug 8, 2019 at 15:34
  • I used NewtonSoft Json for JsonSerialization but getting blank string. Example : newtonsoft.com/json/help/html/SerializingJSON.htm Commented Aug 8, 2019 at 20:39

1 Answer 1

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;
            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.