c# - 从 Json 字典序列化 C# 字典

标签 c# json getter-setter json-serialization

如何在 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;
    }
}

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

Unexpected character encountered while parsing value for Switches

我在这里做错了什么?

最佳答案

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

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

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

或者

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

关于c# - 从 Json 字典序列化 C# 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64758425/

相关文章:

c# - 如何在自动生成的 Edmx 文件中设置 Entity Framework CommandTimeout

c# - 防止在 MVC Ajax.BeginForm 中使用某些条件更新 html?

ios - google places api 没有给我任何结果

ios - 无法分配给属性 'observationTime' 是一个只读属性

Java Getter 和 Setter 问题

javascript - 跨浏览器的 Getter 和 Setter

c# - Unity插件:编码(marshal)C++ double *将C#中的数组翻倍

c# - IDictionary 到字符串

json - Api 蓝图和长时间运行的作业

javascript - 如何在javascript中将数组转换为JSON