Converting dynamic type to dictionary C#

前端 未结 7 1255
执念已碎
执念已碎 2021-01-01 11:22

I have a dynamic object that looks like this,

 {
    \"2\" : \"foo\",
    \"5\" : \"bar\",
    \"8\" : \"foobar\"
 }

How can I convert this

7条回答
  •  庸人自扰
    2021-01-01 12:04

    If the dynamic value in question was created via deserialization from Json.Net as you mentioned in your comments, then it should be a JObject. It turns out that JObject already implements IDictionary, so you can use it as a dictionary without any conversion, as shown below:

    string json = 
         @"{ ""blah"" : { ""2"" : ""foo"", ""5"" : ""bar"", ""8"" : ""foobar"" } }";
    
    var dict = JsonConvert.DeserializeObject>(json);
    dynamic dyn = dict["blah"];
    
    Console.WriteLine(dyn.GetType().FullName);     // Newtonsoft.Json.Linq.JObject
    Console.WriteLine(dyn["2"].ToString());        // foo
    

    If you would rather have a Dictionary instead, you can convert it like this:

    Dictionary newDict = 
              ((IEnumerable>)dyn)
                         .ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString());
    

提交回复
热议问题