我有这个 JSON:
{
"AutoRefreshEnabled" : false,
"AutoRefreshInterval" : 1,
"AutoCycleEnabled" : false,
"AutoCycleInterval" : 1,
"Tabs" : {
"RadTab_Home",
"Dashboard"
},
"CommandName" : "Update Global Settings"
}
我试图将其存储在此类中,但我不确定如何处理嵌入的 Tabs 对象。可能存在大于 0 的任意数量的选项卡(因此 1+,第一个选项卡的键始终是 RadTab_Home)。标签不应该是string[]
。我希望它是一个Dictionary<string, string>
,但我不确定如何表达。
[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<string, string> 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<string, string> Tabs { get; set; }
}
编辑:选项卡现在不返回任何数据,但不会引发错误。
编辑:DataContractJsonSerializer 不支持反序列化到字典。然而,JSON.net 可以!
编辑:使用 Newtonsoft 的 JSON 反序列化器,代码可以完美运行。