将动态类型转换为字典C# [英] Converting dynamic type to dictionary C#

查看:1166
本文介绍了将动态类型转换为字典C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态对象,看起来像这样,

I have a dynamic object that looks like this,

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

如何将其转换为字典

推荐答案

如果您在评论中提到的动态值是通过反序列化从Json.Net创建的,那么它应该是一个 JObject 。事实证明, JObject 已经实现了 IDictionary< string,JToken> ,所以你可以使用它作为字典,没有任何转换,如下所示:

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

如果你宁愿拥有一个字典< string,string> 而不是你可以这样转换:

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());

这篇关于将动态类型转换为字典C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆