I have this JSON:
{
"AutoRefreshEnabled" : false,
"AutoRefreshInterval" : 1,
"AutoCycleEnabled" : false,
"AutoCycleInterval" : 1,
"Tabs" : {
"RadTab_Home",
"Dashboard"
},
"CommandName" : "Update Global Settings"
}
I’m trying to store it in this class, but I am not sure how to handle the embedded Tabs object. There may be an arbitrary number of tabs greater than 0 (so 1+, the first one’s key always being RadTab_Home). Tabs shouldn’t be a string[]. I want it to be a Dictionary<string, string>, but I am unsure how to express that.
[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; }
}
EDIT: Tabs does not return any data now, but no error is thrown.
EDIT: DataContractJsonSerializer does not support deserializing to a dictionary. JSON.net, however, does!
EDIT: Code worked perfectly using Newtonsoft’s JSON deserializer.
If you want the
Tabsproperty to be aDictionary<string, string>then your representation in JSON is incorrect. Currently, you have:And it should be a
string[]. If you want a mapping (i.e.Dictionary<string, string>), then you need a key to associate with the values, and therefore, a different representation in JSON:With this, you can definitely create a
Dictionary<string, string>, as you would have a key to associate with the values. The key would be to create a class, like so:And then define your
Tabsproperty like so:Which you can easily convert to a
Dictionary<string, string>using LINQ:You could add it as a method on your class, but that’s a design decision for you to make (I didn’t add it to the class because I assume this is a data-transfer object).