我需要循环通过web的应用程序设置集合。配置并在JSON字符串中添加键值对。我用的是JSON.Net。我如何在for循环内准备一个JSON字符串?谢谢你!
foreach (string key in ConfigurationManager.AppSettings)
{
string value = ConfigurationManager.AppSettings[key];
}
因为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);
扩展Mehrzad Chehraz的答案,对于那些不需要遍历AppSettings键的人:
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;
}