【问题标题】:deserializing Static properties using json.net?使用 json.net 反序列化静态属性?
【发布时间】:2014-03-24 09:33:56
【问题描述】:

大家好,我有一个像下面这样的 JSON

{
  "totals": {
    "tokenType": "string",
    "tokenDenomination": "double",
    "count": "int"
  },
  "IDCode": "string",
  "Key": "string"
}

反序列化到对象的c#代码是

internal class GetTokenRootInfo
{
    public  static Totals totals{ get; set;}
    public  static string IDCode{ get; set;}
    public  static string Key{ get; set;}
}

当我使用jsonconvert.DeserializeObject<gettokenrootinfo>(json); 什么都没有设置,每个 var 都是 null。

但如果我删除静态类型,那么一切正常。

谁能告诉我反序列化对象时静态类型不起作用的原因?

【问题讨论】:

  • 因为它们是静态的?说真的,我猜可能存在对静态成员的一些滥用,因为将数据反序列化为静态成员没有多大意义。
  • @KeithPayne 一个例外是当您使用静态配置类时。配置静态以方便访问很有用。静态构造函数可以从磁盘加载属性并设置它们。 (反)序列化配置类意味着您可以简单地使用我们Config.MaxConnectionsConfig.Save()Config.Load() 等...
  • @Keith:非常有用;在很多情况下,应用可能需要访问全局设置才能运行;建立一些装饰性的脚手架来访问数据不一定是优先事项。

标签: c# json json.net


【解决方案1】:

如果你真的想反序列化为类的静态成员,你可以用[JsonProperty] 属性显式地标记它们,这样它就可以工作了:

internal class GetTokenRootInfo
{
    [JsonProperty("totals")]
    public static Totals totals { get; set; }
    [JsonProperty("IDCode")]
    public static string IDCode { get; set; }
    [JsonProperty("Key")]
    public static string Key { get; set; }
}

【讨论】:

  • 谢谢@brain 是的,经过一番研究,我已经完成了。
猜你喜欢
  • 1970-01-01
  • 2015-04-20
  • 2020-06-08
  • 2021-05-26
  • 1970-01-01
  • 2011-01-16
  • 2023-03-12
  • 1970-01-01
相关资源
最近更新 更多