Converting dynamic type to dictionary C#

前端 未结 7 1244
执念已碎
执念已碎 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 11:57

    Another way is using System.Web.Helpers.Json included in .NET 4.5.

    Json.Encode(object) and Json.Decode. Like:

    Json.Decode<Generic.Dictionary<string, string>>(value);
    

    MSDN: https://msdn.microsoft.com/en-us/library/gg547931(v=vs.111).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

    Regards, MarianoC.

    0 讨论(0)
  • 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<string, JToken>, 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<Dictionary<string, dynamic>>(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<string, string> instead, you can convert it like this:

    Dictionary<string, string> newDict = 
              ((IEnumerable<KeyValuePair<string, JToken>>)dyn)
                         .ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString());
    
    0 讨论(0)
  • 2021-01-01 12:06

    You can use a RouteValueDictionary to convert a C# object to a dictionary. See: RouteValueDictionary Class - MSDN. It converts object properties to key-value pairs.

    Use it like this:

    var toBeConverted = new {
        foo = 2,
        bar = 5,
        foobar = 8
    };
    
    var result = new RouteValueDictionary(toBeConverted);
    
    0 讨论(0)
  • 2021-01-01 12:09

    You can use Json.Net to deserialize it to dictionary.

    string json = dynamicObject.ToString(); // suppose `dynamicObject` is your input
    Dictionary<string, string> dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
    
    0 讨论(0)
  • 2021-01-01 12:16

    Very similar to ema answer, but with a one-liner using LINQ magic:

    Dictionary<string, object> myDict = sourceObject.GetType().GetProperties().ToDictionary(prop => prop.Name, prop => prop.GetValue(sourceObject, null));
    
    0 讨论(0)
  • 2021-01-01 12:22

    You can fill the dictionary using reflection:

    public Dictionary<String, Object> Dyn2Dict(dynamic dynObj)
    {
         var dictionary = new Dictionary<string, object>();
         foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(dynObj))
         {
            object obj = propertyDescriptor.GetValue(dynObj);
            dictionary.Add(propertyDescriptor.Name, obj);
         }
         return dictionary;
    }
    
    0 讨论(0)
提交回复
热议问题