4

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?

Matthew Faigan
  • 85
  • 1
  • 1
  • 9

1 Answers1

4

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());
André Sampaio
  • 309
  • 1
  • 5