如何使用web.config appsettings中的键/值对创建JSON字符串?

时间:2015-05-15 20:13:31

标签: c# json.net

我需要遍历web.config的app设置集合,并在JSON字符串中添加键值对。我正在使用JSON.Net。如何在for循环中准备JSON字符串?谢谢!

foreach (string key in ConfigurationManager.AppSettings)
{
    string value = ConfigurationManager.AppSettings[key];
}

2 个答案:

答案 0 :(得分:8)

由于AppSettingsNameValueCollection,因此无法将其直接转换为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;
}