Today I am trying to convert a Dictionary<string, string>
to a multi-level JSON object/string. The Dictionary
contains keys like namespaces.
The class
can be as follows:
public static class SettingsConverter
{
public static string Convert()
{
Dictionary<string, string> settings = new Dictionary<string, string>
{
{ "settings.common.enabled", "true" },
{ "settings.common.welcome", "Welcome {0}" },
{ "settings.ui.style", "dark" },
{ "properties.help", "www.google.com" },
{ "properties.user.firstname", "John" },
{ "properties.user.lastname", "Doe" }
};
string json = JsonConvert.SerializeObject(settings, Formatting.Indented);
return json;
}
}
The result I want, should be:
{
"settings":{
"common":{
"enabled":"true",
"welcome":"Welcome {0}"
},
"ui":{
"style":"dark"
}
},
"properties":{
"help": "www.google.com",
"user":{
"firstname":"John",
"lastname":"Doe"
}
}
}
How it is possible to perform this and do I need a custom JsonConverter
for this?
Rather than a flat dictionary of <string, string>, create a multi-level dictionary...
var settings = new Dictionary<string, object>()
{
{
"settings", new Dictionary<string, object>()
{
{
"common", new Dictionary<string, object>()
{
{"enabled", "false"},
{"welcome", "Welcome {0}"}
}
}
}
}
};
That should serialize how you require.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.