如何在 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/