【发布时间】:2019-01-18 01:33:34
【问题描述】:
假设我在 C# 中有以下类。
class MyClass
{
[JsonIgnore]
public Foo Foo { get; set; }
[JsonProperty("bar")]
private Bar Bar
{
get
{
return new Bar()
{
Foo = this.Foo,
}
}
set
{
this.Foo = value.Foo;
}
}
}
现在假设我创建了以下实例:
var instance = new MyClass()
{
Foo = new Foo(){//init properties of Foo};
}
这会正确序列化为 json,但不会反序列化。 Bar.set() 似乎永远不会被调用。知道为什么吗?我一直在浏览 Newtonsoft 文档以寻找线索,但还没有发现任何有用的东西。
【问题讨论】:
-
Bar 集中没有 Foo,因为它被忽略了
-
根据提供的示例,此类的假定设计是有问题的。
-
与Why are all the collections in my POCO are null when deserializing some valid json with the .NET Newtonsoft.Json component中的问题基本相同,即在填充preallocated引用类型对象属性时,Json.NET不会调用setter来重置物体回来了——因为,大概,它一开始就在那里。使用
ObjectCreationHandling.Replace的解决方法也应该在这里工作。或者,您可以在反序列化时预分配Foo,或者让Bar有一个指向它的活动指针。 -
另外,
Bar是什么样的?它是为了在将MyClass.Bar序列化为 JSON 时引入一些额外的嵌套而创建的纯 DTO,还是有其他一些责任? -
是的,Bar 是一个提供嵌套级别的 DTO。我同意这个类的设计不是最好的。或许,我应该翻转一下,让
Foo成为计算属性。