canton7 / Stylet

A very lightweight but powerful ViewModel-First MVVM framework for WPF for .NET Framework and .NET Core, inspired by Caliburn.Micro.
MIT License
995 stars 144 forks source link

System.Text.Json Json serialization / deserialization fails #339

Closed phamilton4321 closed 7 months ago

phamilton4321 commented 2 years ago

Description Stylet/PropertyChangedBase.cs is missing the attribute [System.Text.Json.Serialization.JsonIgnore] to make classes serializable and deserializable.

To Reproduce

public class Test : Stylet.PropertyChangedBase
{
 public string TestString {get; set; }
}

can be serialized, but has a "PropertyChangedDispatcher": {} object which can't be deserialized.

Version Info

Solution

[System.Xml.Serialization.XmlIgnore]
[System.Text.Json.Serialization.JsonIgnore]
public virtual Action<Action> PropertyChangedDispatcher
{
    get { return this._propertyChangedDispatcher; }
    set { this._propertyChangedDispatcher = value; }
}
Catalan-1ap commented 2 years ago

Description Stylet/PropertyChangedBase.cs is missing the attribute [System.Text.Json.Serialization.JsonIgnore] to make classes serializable and deserializable.

To Reproduce

public class Test : Stylet.PropertyChangedBase
{
 public string TestString {get; set; }
}

can be serialized, but has a "PropertyChangedDispatcher": {} object which can't be deserialized.

Version Info

  • Stylet version: 1.3.6
  • Runtime version: 6.0.1

Solution

[System.Xml.Serialization.XmlIgnore]
[System.Text.Json.Serialization.JsonIgnore]
public virtual Action<Action> PropertyChangedDispatcher
{
    get { return this._propertyChangedDispatcher; }
    set { this._propertyChangedDispatcher = value; }
}

You could serialize only what you want. Just mark your class with [JsonObject(MemberSerialization.OptIn)] and properties to serialize with [JsonProperty].

For more info see docs

phamilton4321 commented 2 years ago

That would also solve it, but in my opinion is more like a workaround. Especially because the xaml ignore attribute exist in your code.

canton7 commented 2 years ago

Scheduled for the next release.

Note that I strongly recommend against serializing ViewModels. They're not meant to be serialized. Create a dedicated model that's meant to be serialized instead.

phamilton4321 commented 2 years ago

Thanks a lot! I know and normally I'm against it too. But when I found this, I had to use the VM...

canton7 commented 2 years ago

(this will be closed when the next release is merged)