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

标签 c# json.net reactiveui

我正在尝试将一些 json 反序列化为一些继承自 Reactive UI 的 ReactiveObject 类的简单对象。由于某种原因,这些属性永远不会在那里被填充。使用 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

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

关于c# - 从 Json 反序列化从 ReactiveObject 继承的对象不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51161909/

相关文章:

c# - 简化将 List<DateTime> 转换为 SortedSet<long>

c# - Visual Studio 安装项目 : How Can I force an Uninstaller to run in Administrator mode?

c# - UWP - 框架导航似乎会导致非托管内存泄漏

c# - 如何在 json.net 中将空字符串反序列化为枚举

winforms - 如何为子 UserControl 实现 IActivationForViewFetcher?

c# - Silverlight ItemsControl 行为 : how do i get an item i click on?

C# 使用 HttpWebResponse 获取 JSON 编码的字典以及错误的状态代码

c# - 从 sql server 读取数据时检测到自引用循环

winforms - 如何在ReactiveUI 6.5中显示新的模态表单

c# - 使用 ReactiveUI 7 调用命令参数