【问题标题】:Property not getting serialized in Json via newtonsoft属性未通过 newtonsoft 在 Json 中序列化
【发布时间】:2020-11-06 05:19:37
【问题描述】:

在类中定义了许多属性,但其中一个属性没有被序列化(使用 newtonsoft),下面提到了该属性:

public override string Value
{​​​​
  set    
  {
​​​​
    if (value == null)    
    {    ​​​​
       this.Null = true;    
    }​​ ​ ​
    else if (value == string.Empty)
    {    ​​​​
       _A = string.Empty;    
       _P = string.Empty;    
       _S = string.Empty;    
    }​​​ ​
    else
    {​​​ ​

         value = _A + _P + _S;    
     }​​​​

   }​​​​    
}

但是当我们在属性中定义 getter 时,它会被序列化,所以请建议;我们不想将 getter 放在属性中。

【问题讨论】:

    标签: c# .net asp.net-core .net-core visual-studio-2019


    【解决方案1】:

    [JsonProperty] 属性设置为您的属性。 但总的来说,您可以将您的 getter 设置为 private - 这样您就不会将数据暴露给其他类,但它可以帮助解决您的问题。

    【讨论】:

    • 感谢您的宝贵时间,但问题是我们无法更改代码;直到我们有一个具体的原因,所以请告诉我为什么我们必须放置 [jsonproperty] 属性,因为 newtonsoft 已经满足了这一点
    【解决方案2】:

    好吧,首先,你没有得到如何将 json 现在序列化它,也许让它成为一个看起来很有趣的方法,只在一个属性上设置一个集合。如果你想填充你的字段,只需告诉 json 使用注释来做到这一点

    [JsonProperty("_A")]
    private string _A ;
    
    [JsonProperty("_P")]
    private string _P ;
    
    [JsonProperty("_S")]
    private string _S;
    
    [JsonIgnore]
    public override string Value
    {​​​​
      set    
      {
    ​​​​
        if (value == null)    
        {    ​​​​
           this.Null = true;    
        }​​ ​ ​
        else if (value == string.Empty)
        {    ​​​​
           _A = string.Empty;    
           _P = string.Empty;    
           _S = string.Empty;    
        }​​​ ​
        else
        {​​​ ​
    
             value = _A + _P + _S;    
         }​​​​
    
       }​​​​    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多