I'm testing out Json.Net in preparation for a different project, and I'm having some trouble. What I want to do is convert the content of moretests
to a 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. Can anybody help me out?