动态地将JSON反序列化为C#字典

时间:2017-09-26 06:00:13

标签: c# json dictionary serialization

我有一个JSON文件我试图反序列化到一个带有字典作为值的列表,但是努力以一种好的格式获取输出并且在它被反序列化后努力索引/解析它。我是新手,非常感谢他们的帮助。我希望键/值对看起来像:{" greeting" :[" greet1":"嘿"," greet2" :"嗨"]}

下面的JSON文件:

{
"greeting": [
        {
          "greet1": "hey",
          "greet2": "hi"
        }
      ],
"bye": [
        {
          "bye1": "adios"
        }
      ]
}

尝试过的代码:

public static Dictionary<string, List<Dictionary<string, string>>> jsonResponses = new Dictionary<string, List<Dictionary<string, string>>>();

public static void DeserializeJsonDict()
{
    string jsonURL = HttpContext.Current.Server.MapPath("./theFile.json");

    using (var webClient = new System.Net.WebClient())
    {
        var jsonData = webClient.DownloadString(jsonURL);
        jsonResponses = JsonConvert.DeserializeObject<Dictionary<string, List<Dictionary<string, string>>>>(jsonData);

    }

}

2 个答案:

答案 0 :(得分:0)

var str = @"{'greeting':[{'greet1': 'hey','greet2': 'hi'}],'bye': [{'bye1': 'adios'}]}";    
var data = JsonConvert.DeserializeAnonymousType(str, new Dictionary<dynamic, dynamic>());

您可以直接推荐属性,例如data.greeting。此外,还有一种方法可以遍历转换结果 - 使用KeyValuePair<string, dynamic>作为泛型类型参数可以迭代动态值,例如

foreach (var i in data){
  Console.WriteLine(i.Key);
  foreach(var v in i.Value) Console.WriteLine(v); 
}

https://dotnetfiddle.net/UUvMeA

答案 1 :(得分:-1)

string json = @"{""key1"":""value1"",""key2"":""value2""}";

var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);