如何将Dictionary <string,string>添加到现有的JSON.Net的JObject?

Mas*_*iti 17 json.net

我有一个通过解析一些JSON文本创建的JObject(使用JSON.Net).我正在直接操作,在这个JObject的顶层添加键.当我添加的值是一个字符串时,我没有问题:

json["newkey"] = "New Value"; // works
Run Code Online (Sandbox Code Playgroud)

但如果我能弄清楚如何添加词典,我会被诅咒,例如:

Dictionary<string,string> dict = new Dictionary<string,string>();
dict["one"] = "1";
dict["two"] = "2";
json["dict"] = dict;          // fails
Run Code Online (Sandbox Code Playgroud)

我已经完成了相当多的谷歌搜索和阅读JSON.Net文档,但一切似乎都是将JSON文本理解为JObject,或者使用序列化将.NET对象编写为JSON文本.或者使用一些花哨的LINQ语句来处理复杂对象的各种事情......

我试过这些,没有一个有效:

json["dict"] = new JObject(dict);
json["dict"] = new JObject((Dictionary<string,string>)dict);
json["dict"] = new JArray(dict);  // desperation sets in :)
json["dict"] = (JObject)dict;     // please dear god let this work
Run Code Online (Sandbox Code Playgroud)

我遇到的大多数最新错误是:

无法确定类型System.Collections.Generic.KeyValuePair`2 [System.String,System.String]的JSON对象类型.

Vit*_*nin 42

我相信你正在寻找这样的东西:

json["dict"] = JObject.FromObject(dict);
Run Code Online (Sandbox Code Playgroud)