如何将点表示法转换为json
点符号可以具有任何深度
所有数据都是这样的:
Dictionary<string, string> data = new Dictionary<string, string>
{
{"Company.Website", "Hjemmeside"},
{"Company.TextHeaderPlaceholder", "Firmanavn"},
{"Company.User.Manager.Repositories.CreateAsync.ArgumentNullException.InvalidCompanyId", "firma id fejl"},
{"BookingSettings.HelpText", "Hjælpe tekst på webshop"},
{"BookingSettings.OnGoingOrderValidation.Text", "Bestillings validering i gang"},
{"BookingSettings.OnGoingOrderValidation.Created", "Oprettet"},
{"BookingSettings.Url", "Kundelink til booking"}
};
Json结果应该是:
{
"Company": {
"Website": "Hjemmeside",
"TextHeaderPlaceholder": "Firmanavn",
"Users": {
"Managers": {
"Repositories": {
"CreateAsync": {
"ArgumentNullException": {
"InvalidCompanyId": "Can not create company user with out a company!"
}
}
}
}
}
},
"BookingSettings": {
"HelpText": "Hjælpe tekst på webshop",
"OnGoingOrderValidation": {
"Text": "Bestillings validering i gang",
"Created": "Oprettet"
},
"URL": "Kundelink til booking"
}
}
这很简单吗?
答案 0 :(得分:0)
我将反序列化为嵌套字典。
public static Dictionary<string, object> DotNotationToDictionary(Dictionary<string, string> dotNotation)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
foreach (var dotObject in dotNotation)
{
var hierarcy = dotObject.Key.Split('.');
Dictionary<string, object> bottom = dictionary;
for (int i = 0; i < hierarcy.Length; i++)
{
var key = hierarcy[i];
if (i == hierarcy.Length - 1) // Last key
{
bottom.Add(key, dotObject.Value);
}
else
{
if (!bottom.ContainsKey(key))
bottom.Add(key, new Dictionary<string, object>());
bottom = (Dictionary<string, object>) bottom[key];
}
}
}
return dictionary;
}
然后,您可以只使用JsonConvert.SerializeObject
(来自Newtonsoft.Json)来将字典转换为JSON。
Dictionary<string, string> dotNotation = new Dictionary<string, string>
{
{"Company.Website", "Hjemmeside"},
{"Company.TextHeaderPlaceholder", "Firmanavn"},
{"Company.User.Manager.Repositories.CreateAsync.ArgumentNullException.InvalidCompanyId", "firma id fejl"},
{"BookingSettings.HelpText", "Hjælpe tekst på webshop"},
{"BookingSettings.OnGoingOrderValidation.Text", "Bestillings validering i gang"},
{"BookingSettings.OnGoingOrderValidation.Created", "Oprettet"},
{"BookingSettings.Url", "Kundelink til booking"}
};
var betterDictionary = DotNotationToDictionary(dotNotation);
var json = JsonConvert.SerializeObject(betterDictionary);
Console.WriteLine(json);
这是输出(格式化):
{
"Company": {
"Website": "Hjemmeside",
"TextHeaderPlaceholder": "Firmanavn",
"User": {
"Manager": {
"Repositories": {
"CreateAsync": {
"ArgumentNullException": {
"InvalidCompanyId": "firma id fejl"
}
}
}
}
}
},
"BookingSettings": {
"HelpText": "Hjælpe tekst på webshop",
"OnGoingOrderValidation": {
"Text": "Bestillings validering i gang",
"Created": "Oprettet"
},
"Url": "Kundelink til booking"
}
}