Removing JSON deserialization in C # - an attempt to turn an associative JSON array into a dictionary <string, string>
I have this JSON:
{
"AutoRefreshEnabled" : false,
"AutoRefreshInterval" : 1,
"AutoCycleEnabled" : false,
"AutoCycleInterval" : 1,
"Tabs" : {
"RadTab_Home",
"Dashboard"
},
"CommandName" : "Update Global Settings"
}
I am trying to save it in this class, but I'm not sure how to handle the Tabs inline object. There may be an arbitrary number of tabs greater than 0 (so 1+, the first key will always be RadTab_Home). Tabs should not be string[]. I want it to be Dictionary<string, string>, but I'm not sure how to put it.
[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 no longer return data, but no error occurs. EDIT: DataContractJsonSerializer does not support dictionary deserialization. JSON.net, however, does! EDIT: The code worked perfectly with the Newtonsoft JSON deserializer.
, Tabs Dictionary<string, string>, JSON . :
"Tabs" : [
"RadTab_Home",
"Dashboard"
],
string[]. (.. Dictionary<string, string>), , , JSON:
"Tabs" : [
{ "key1" : "RadTab_Home" },
{ "key2" : "Dashboard" }
],
Dictionary<string, string>, . , :
// 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; }
Dictionary<string, string> LINQ:
// Deserialized instance.
MyClass instance = ...;
// Map
IDictionary<string, string> tabsMap = instance.Tabs.
ToDictionary(p => p.Key, p => p.Value);