Reputation: 2902
I need to loop through the app settings collection of web.config and add the key value pairs in a JSON string. I am using JSON.Net. How can I prepare a JSON string inside the for loop? Thank you!
foreach (string key in ConfigurationManager.AppSettings)
{
string value = ConfigurationManager.AppSettings[key];
}
Upvotes: 2
Views: 3149
Reputation: 5147
Since AppSettings is a NameValueCollection, you cannot convert it directly to Json. You should populate a Dictionary from it and serialize it using the JsonConvert class:
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);
Upvotes: 8
Reputation: 1743
Extending Mehrzad Chehraz's answer, for those who don't need to iterate through the AppSettings keys:
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;
}
Upvotes: 3