【问题标题】:Serialize Dictionary in C# from Json Dictionary从 Json 字典中序列化 C# 中的字典
【发布时间】:2020-11-09 19:56:20
【问题描述】:

如何在 JSON 中定义一个可以在 C# 中解析的字典?

这是我需要解析的 Json:

  "InputRequest": 
        {
            "Switches":  {"showButton": true}
        }

这是我的例子:

 public class InputRequest
{
    [JsonProperty(PropertyName="Switches")]
    public ReadOnlyDictionary<string, bool> Switches { get; }
}

由于某种原因,它无法解析,并显示 Switches 参数的 null 值。

我的另一种方法是创建一个新参数并将字典作为字符串:

 public class InputRequest
{
    [JsonProperty(PropertyName="Switches")]
    public string Switches { get; }

    public ReadOnlyDictionary<string, bool> SwitchesDictionary 
    {
          var values = JsonConvert.DeserializeObject<ReadOnlyDictionary<string, bool>>(Switches);
          return values;
    }
}

对于这种方法,它显示错误

解析 Switch 的值时遇到意外字符

我在这里做错了什么?

【问题讨论】:

    标签: c# json getter-setter json-serialization


    【解决方案1】:

    您正在使用只读集合,并且您没有提供 setter。

    要么将您的集合类型更改为普通的Dictionary&lt;string,bool&gt; 并将其初始化为反序列化程序可以添加内容的集合,或者将set; 添加到您的属性,以便反序列化程序可以将值设置为新集合它创建。

    public ReadOnlyDictionary<string, bool> Switches { get; set; }
    

    public IDictionary<string, bool> Switches { get; } = new Dictionary<string, bool>();
    

    【讨论】:

      【解决方案2】:

      JSON.NET 查找“Switches”,但您可能正在查找“InputRequest.Switches”。尝试将“Switches”对象放在全局空间中,如下所示:

      {
         "Switches":  
         {
             "showButton": true
         }
      }
      

      然后,您可以将 JSON 字符串反序列化为 InputRequest 对象,如下例所示:

      string json = "{\"Switches\": { \"showButton\": true } }";
      var myObject = JsonConvert.DeserializeObject<InputRequest>(json);
      

      更新:

      您的ReadOnlyDictionary&lt;string, bool&gt; 没有设置器,您需要像这样添加设置器:

      public ReadOnlyDictionary<string, bool> Switches { get; set; }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-17
        • 2015-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多