繁体   English   中英

从 Json 字典序列化 C# 中的字典

[英]Serialize Dictionary in C# from Json Dictionary

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

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

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

我在这里做错了什么?

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

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

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

或者

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

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

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

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

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

更新:

你的ReadOnlyDictionary<string, bool>没有 setter,你需要像这样添加一个 setter:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM