我需要遍历web.config的app设置集合,并在JSON字符串中添加键值对。我正在使用JSON.Net。如何在for循环中准备JSON字符串?谢谢!
foreach (string key in ConfigurationManager.AppSettings)
{
string value = ConfigurationManager.AppSettings[key];
}
答案 0 :(得分:8)
由于AppSettings是NameValueCollection,因此无法将其直接转换为Json。您应该从中填充Dictionary并使用JsonConvert类序列化它:
Dictionary<string, string> items = new Dictionary<string, string>();
foreach (string key in ConfigurationManager.AppSettings) {
string value = ConfigurationManager.AppSettings[key];
items.Add(key, value);
}
string json = JsonConvert.SerializeObject(items, Formatting.Indented);
答案 1 :(得分:3)
为那些不需要遍历AppSettings键的人扩展Mehrzad Chehraz's answer:
public string GetJsonNetSerializedString()
{
var keys = ConfigurationManager.AppSettings.AllKeys
.Select(key => new
{
Key = key,
Value = ConfigurationManager.AppSettings[key]
});
string json = JsonConvert.SerializeObject(keys, Formatting.Indented);
return json;
}