【问题标题】:Deserializing Calculated Properties with Setters使用 Setter 反序列化计算属性
【发布时间】: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 成为计算属性。

标签: c# .net json.net


【解决方案1】:

基于 cmets,我想出了以下似乎可行的解决方案。

class MyClass
{
  private Bar _bar = new Bar();

  [JsonIgnore]
  public Foo Foo
  {
     get { return Bar.Foo; }
     set { Bar.Foo = value; }
  }

  [JsonProperty("bar")]
  private Bar Bar
  {
    get
    {
      // there's some validation logic that goes here
      return _bar;
    }
    set
    {
      _bar = value;
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-13
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    相关资源
    最近更新 更多