M
M
Michael2021-03-25 16:11:37
C++ / C#
Michael, 2021-03-25 16:11:37

How to serialize ObservableCollection interface?

Hello.
I have a module that implements an interface

[DataContract]
class LineModule1VM : BaseVM,  ILineModule1
    {
        [DataMember]
        public ObservableCollection<FoundLine> FoundDataLines { get; set; } = new ObservableCollection<FoundLine>();

        public ObservableCollection<Line> Lines { get; set; }

interface ILineModule1 : ILineModule
    {
        [DataMember]
        public double D { get; set; }
    }


interface ILineModule
    {
        [DataMember]
        public ObservableCollection<FoundLine> FoundDataLines { get; set; }
        [DataMember]
        public ObservableCollection<Line> Lines { get; set; }
    }


and there is a main VM
[DataContract]
[KnownType(typeof(LineModule1VM))]
class ListBoxItemVM : BaseVM
    {      
[DataMember]
        public ObservableCollection<ILineModule1> lineModule1Items { get; set; } = new ObservableCollection<ILineModule1>();
}


serialization
using (FileStream fs = new FileStream(saveFileDialog.FileName, FileMode.Create))
                {
                    var ser = new DataContractSerializer(typeof(DataProgram));
                    ser.WriteObject(fs, DataToSave);
                }


deserialization
using FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open);

                var serTest = new DataContractSerializer(typeof(DataProgram));

                var DataTest = (DataProgram)serTest.ReadObject(fs);

I get an error
Вызвано исключение: "System.Runtime.Serialization.SerializationException" в System.Private.DataContractSerialization.dll
Необработанное исключение типа "System.Runtime.Serialization.SerializationException" в System.Private.DataContractSerialization.dll
Type 'Baser.ViewModels.Module1.LineModule1VM' with data contract name 'LineModule1VM :http://schemas.datacontract.org/2004/07/Baser.ViewModels.Modules1' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.


I don't understand how I can set the KnownTypeAttribute to make it work. What's wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2021-03-25
@mscrack

The question is closed. There was also a class where the list was used, the KnownTypeAttribute was not correctly indicated there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question