Jyina Jyina - 16 days ago 18
C# Question

How to create a JSON string with key/value pairs from web.config appsettings?

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];
}

Answer

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);
Comments