如何反序列化包含可变数量的对象的json对象并将它们作为C#中的键值集合?

如何反序列化以下JSON对象并获取Dictionary的集合,其中键(字符串)应该是方法名称,对象是C#中的详细信息。

{ "methods": { "password.2": { "title": "Password CustomerID", "type": "password" }, "ubikey.sms.1": { "title": "SMS", "type": "stepup", "password": "password.2", "stepUp": "sms" }, "tupas.test.1": { "title": "TUPAS Emulator", "type": "proxy" } } } 

如果它是一个方法数组,我可以使用数组轻松地序列化它。 但由于这本身就是一个关键的价值对,我陷入困境。

我正在对特定的api进行WebRequest并将结果作为json。

用于序列化对象的代码来自https://msdn.microsoft.com/en-us/library/hh674188.aspx

您链接的页面描述了如何使用DataContractJsonSerializer反序列化JSON。 您可以使用该序列化程序将"methods"对象反序列化为Dictionary前提是您使用的是.Net 4.5或更高版本,并且还设置了DataContractJsonSerializerSettings.UseSimpleDictionaryFormat = true 。 完成此操作后,您可以定义以下类:

 public class Method { public string title { get; set; } public string type { get; set; } public string password { get; set; } public string stepUp { get; set; } } public class Response { public Dictionary methods { get; set; } } 

并按如下方式解析它们:

  var settings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true }; var jsonSerializer = new DataContractJsonSerializer(typeof(Response), settings); var jsonResponse = jsonSerializer.ReadObject(response.GetResponseStream()) as Response; 

如果您使用的是早期版本的.Net,则可能需要使用其他序列化程序,例如Json.NET ,因为在早期版本中, DataContractJsonSerializer将字典序列化为键/值对数组 。

JSON.net这样做:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string json = @"{ ""methods"": { ""password.2"": { ""title"": ""Password CustomerID"", ""type"": ""password"" }, ""ubikey.sms.1"": { ""title"": ""SMS"", ""type"": ""stepup"", ""password"": ""password.2"", ""stepUp"": ""sms"" }, ""tupas.test.1"": { ""title"": ""TUPAS Emulator"", ""type"": ""proxy"" } } }"; Dictionary>> values = JsonConvert.DeserializeObject>>>(json); } } } 
  dynamic results = JsonConvert.DeserializeObject(JsonString()); Dictionary dictionary = new Dictionary(); foreach (var o in results.methods) { dictionary[o.Name] = o.Value; } private static string JsonString() { return "{\"methods\": {\"password.2\": {\"title\": \"Password CustomerID\",\"type\": \"password\"},\"ubikey.sms.1\": {\"title\": \"SMS\",\"type\": \"stepup\",\"password\": \"password.2\",\"stepUp\": \"sms\"},\"tupas.test.1\": {\"title\": \"TUPAS Emulator\",\"type\": \"proxy\"}}}"; }