反序列化从 Json 继承自 ReactiveObject 的对象不起作用

Deserializing object that inherits from ReactiveObject from Json does not work

我正在尝试将一些 json 反序列化为一些继承自 Reactive UI 的 ReactiveObject class 的简单对象。由于某种原因,这些属性永远不会在那里被填充。使用 POCO 可以毫无问题地工作。

class Program
{
    class Profile
    {
        public string Name { get; set; }
    }

    class ReactiveProfile : ReactiveObject
    {
        private string _name;

        public string Name
        {
            get => _name;
            set => this.RaiseAndSetIfChanged(ref _name, value);
        }
    }

    static void Main(string[] args)
    {
        var profiles = new List<Profile>()
        {
            new Profile() {Name = "Foo"},
            new Profile() {Name = "Bar"}
        };

        var path = @"C:\temp\profiles.json";

        File.WriteAllText(path,
            JsonConvert.SerializeObject(profiles.ToArray(),
                Formatting.Indented,
                new StringEnumConverter()),
            Encoding.UTF8);

        // works
        var pocoProfiles = (Profile[])JsonConvert.DeserializeObject(
            File.ReadAllText(path, Encoding.UTF8),
            typeof(Profile[]));

        // properties not filled
        var reactiveProfiles = (ReactiveProfile[])JsonConvert.DeserializeObject(
            File.ReadAllText(path, Encoding.UTF8),
            typeof(ReactiveProfile[]));

        if (File.Exists(path))
        {
            File.Delete(path);
        }
    }
}

要正确序列化 ReactiveObjects,您应该使用 System.Runtime.Serialization 命名空间的 DataContract 属性。然后用 DataMember 属性标记你想保存的成员,用 IgnoreDataMember 属性标记你不想保存的成员。

所以在你的情况下,是这样的:

[DataContract]
class ReactiveProfile : ReactiveObject
{
    [IgnoreDataMember]
    private string _name;

    [DataMember]
    public string Name
    {
        get => _name;
        set => this.RaiseAndSetIfChanged(ref _name, value);
    }
}

这是 Paul 在 Github 上的一个旧用法示例:link

以及数据持久化的文档link:link

我 运行 您提供的代码进行了此更改,它按预期工作。如果您有任何问题,请告诉我。