将JSON反序列化为C# – 尝试将JSON关联数组转换为Dictionary

我有这个JSON:

{ "AutoRefreshEnabled" : false, "AutoRefreshInterval" : 1, "AutoCycleEnabled" : false, "AutoCycleInterval" : 1, "Tabs" : { "RadTab_Home", "Dashboard" }, "CommandName" : "Update Global Settings" } 

我试图将它存储在这个类中,但我不知道如何处理嵌入的Tabs对象。 可能有大于0的任意数量的选项卡(因此1+,第一个关键字始终为RadTab_Home)。 标签不应该是string[] 。 我希望它是一个Dictionary ,但我不确定如何表达它。

 [DataContract] public class GlobalSettingsJSON { private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public GlobalSettingsJSON() { } public GlobalSettingsJSON(string commandName, string autoRefreshEnabled, string autoRefreshInterval, string autoCycleEnabled, string autoCycleInterval, Dictionary tabs) { Logger.InfoFormat("Command Name: {0}, DockID: {1}, " + "AutoRefreshEnabled: {2}, AutoRefreshInterval: {3}, " + "AutoCycleEnabled: {4}, AutoCycleInterval: {5}", commandName, autoRefreshEnabled, autoRefreshInterval, autoCycleEnabled, autoCycleInterval); CommandName = commandName; AutoRefreshEnabled = autoRefreshEnabled; AutoRefreshInterval = autoRefreshInterval; AutoCycleEnabled = autoCycleEnabled; AutoCycleInterval = autoCycleInterval; Tabs = tabs; } [DataMember(Name = "CommandName")] public string CommandName { get; set; } [DataMember(Name = "AutoRefreshEnabled")] public string AutoRefreshEnabled { get; set; } [DataMember(Name = "AutoRefreshInterval")] public string AutoRefreshInterval { get; set; } [DataMember(Name = "AutoCycleEnabled")] public string AutoCycleEnabled { get; set; } [DataMember(Name = "AutoCycleInterval")] public string AutoCycleInterval { get; set; } [DataMember(Name = "Tabs")] public Dictionary Tabs { get; set; } } 

编辑:选项卡现在不返回任何数据,但不会引发任何错误。 编辑:DataContractJsonSerializer不支持反序列化到字典。 但是,JSON.net呢! 编辑:代码使用Newtonsoft的JSON解串器完美地工作。

如果您希望Tabs属性为Dictionary那么您在JSON中的表示是不正确的。 目前,您有:

 "Tabs" : [ "RadTab_Home", "Dashboard" ], 

它应该是一个string[] 。 如果你想要一个映射(即Dictionary ),那么你需要一个来关联这些值,因此需要一个不同的JSON表示:

 "Tabs" : [ { "key1" : "RadTab_Home" }, { "key2" : "Dashboard" } ], 

有了这个,您绝对可以创建一个Dictionary ,因为您将拥有一个与值关联的键。 关键是要创建一个类,如下所示:

 // NOTE: You can use POCO DataContract serialization for this type. [DataContract] public class Pair { [DataMember] public string Key { get; set; } [DataMember] public string Value { get; set; } } 

然后定义您的Tabs属性,如下所示:

 [DataMember] public Pair[] Tabs { get; set; } 

您可以使用LINQ轻松转换为Dictionary

 // Deserialized instance. MyClass instance = ...; // Map IDictionary tabsMap = instance.Tabs. ToDictionary(p => p.Key, p => p.Value); 

你可以将它作为一个方法添加到你的类中,但这是你做出的设计决定(我没有把它添加到类中,因为我认为这是一个数据传输对象 )。