简体   繁体   English

使用Json.NET将JObject的一部分转换为Dictionary <string, string>

[英]Using Json.NET to convert part of a JObject to Dictionary<string, string>

I'm testing out Json.Net in preparation for a different project, and I'm having some trouble. 我正在测试Json.Net以准备其他项目,但遇到了一些麻烦。 What I want to do is convert the content of moretests to a Dictionary. 我要做的是将moretests的内容转换为Dictionary。 Here's my full code: 这是我的完整代码:

class Program
{
    static void Main(string[] args)
    {
        string json = @"{
        'test': 'a',
        'test2': 'b',
        'moretests':{
            'test3': 'c',
            'test4': 'd'
            }
        }";

        JObject parsed = JObject.Parse(json);

        IDictionary<string, JToken> results = (JObject)parsed["moretests"];

        Dictionary<string, string> results2 = results.ToDictionary(pair => pair.Key, pair => (string)pair.Value);

        foreach (var i in results.Keys)
        {
            Console.WriteLine($"{i}: {results[i]}");
        }
    }
}

I got these 2 lines: 我得到了这两行:

IDictionary<string, JToken> results = (JObject)parsed["moretests"];

Dictionary<string, string> results2 = results.ToDictionary(pair => pair.Key, pair => (string)pair.Value);

from here but I was wondering if it's possible to shorten it to one line. 这里开始,但我想知道是否可以将其缩短为一行。 I tried doing 我试着做

Dictionary<string, string> results = (JObject)parsed["moretests"].ToDictionary(pair => pair.Key, pair => pair.Value)

but it didn't work as in that case pair is no longer a KeyValuePair but instead a JToken. 但它不起作用,因为在这种情况下,该对不再是KeyValuePair,而是一个JToken。 Can anybody help me out? 有人可以帮我吗?

You could use this line 您可以使用此行

Dictionary<string, string> results = ((IDictionary<string, JToken>)(JObject)parsed["moretests"]).ToDictionary(pair => pair.Key, pair => (string)pair.Value);

You may want to avoid doing this though, it really hurts readability. 您可能要避免这样做,但这确实会损害可读性。

Edit 编辑

I messed around with it for a while and got this cleaner version. 我把它弄乱了一段时间,得到了这个更干净的版本。

Dictionary<string, string> results = JsonConvert.DeserializeObject<Dictionary<string, string>>(parsed["moretests"].ToString());

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

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