Jyina
Jyina

Reputation: 2902

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

Upvotes: 2

Views: 3149

Answers (2)

Mehrzad Chehraz
Mehrzad Chehraz

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

Gabriel Rainha
Gabriel Rainha

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

Related Questions