2

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

2 Answers 2

8

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.