我正在尝试将一些 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/