[英]Serialize model that inherits from ObservableObject
I want to serialize and deserialize a model object that inherits from MvvmLight.ObservableObject
.我想序列化和反序列化从 MvvmLight.ObservableObject 继承的
MvvmLight.ObservableObject
。 Trying to deserialize the object with System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject
throws a System.Runtime.Serialization.InvalidDataContractException
with the info that the base class (ie MvvmLight.ObservableObject
) doensn't have the DataContractAttribute
or SerializableAttribute
. Trying to deserialize the object with
System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject
throws a System.Runtime.Serialization.InvalidDataContractException
with the info that the base class (ie MvvmLight.ObservableObject
) doensn't have the DataContractAttribute
or SerializableAttribute
. My model that don't work looks like that:我的 model 不工作看起来像这样:
using GalaSoft.MvvmLight;
[DataContract]
public class MyModel : ObservableObject
{
[IgnoreDataMember]
private int _id;
[DataMember]
public int Id
{
get => _id;
set => Set(ref _id, value);
}
}
After removing [DataContract]
there's no exception but also no deserialized data.删除
[DataContract]
后没有异常,也没有反序列化数据。
A solution could be to create a copy of MyModel
called MyModelSerializable
with the same properties but that don't inherit from ObservableObject and use that for serializing.一种解决方案可能是创建一个名为
MyModelSerializable
的MyModel
副本,该副本具有相同的属性,但不继承自 ObservableObject 并将其用于序列化。 After deserializing, the MyModel
objects could be created with the data of the MyModelSerializable
objects.反序列化后,可以使用
MyModel
对象的数据创建MyModelSerializable
对象。 Is there a better solution?有更好的解决方案吗?
Edit: As requested a link to the code of GalaSoft.MvvmLight.ObservableObject
: https://github.com/lbugnion/mvvmlight/blob/master/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(PCL)/ObservableObject.cs编辑:根据要求,链接到
GalaSoft.MvvmLight.ObservableObject
的代码: https://github.com/lbugnion/mvvmlight/blob/master/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(PCL)/ObservableObject.cs
You cant use DataContract Attribute here if you cant mark the ObservableObject with DataContract.如果不能用 DataContract 标记 ObservableObject,则不能在此处使用 DataContract 属性。 SO in your case i think you couldnt mark the ObservableObject.
所以在你的情况下,我认为你不能标记 ObservableObject。
You have to Create another Class with the desired items you want to serialize without class derived ObservableObject您必须使用要序列化的所需项目创建另一个 Class 而无需 class 派生的 ObservableObject
Maybe You could implement (in another Serialized Class with DataContract Attribute which sees MyModel) in your project:也许您可以在您的项目中实现(在另一个带有 DataContract 属性的序列化 Class 中看到 MyModel):
[OnSerializing]
void PrepareForSerialization(StreamingContext sc)
{
//get items from MyModel and inject in new class serializable
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.