how to convert NameValueCollection to JSON string?

One way to serialize NameValueCollection is by first converting it to Dictionary and then serialize the Dictionary. To convert to dictionary:

thenvc.AllKeys.ToDictionary(k => k, k => thenvc[k]);

If you need to do the conversion frequently, you can also create an extension method to NameValueCollection:

public static class NVCExtender
{
    public static IDictionary<string, string> ToDictionary(
                                        this NameValueCollection source)
    {
        return source.AllKeys.ToDictionary(k => k, k => source[k]);
    }
}

so you can do the conversion in one line like this:

NameValueCollection Data = new NameValueCollection();
Data.Add("Foo", "baa");

var dict = Data.ToDictionary();

Then you can serialize the dictionary:

var json = new JavaScriptSerializer().Serialize(dict);
// you get {"Foo":"baa"}

But NameValueCollection can have multiple values for one key, for example:

NameValueCollection Data = new NameValueCollection();
Data.Add("Foo", "baa");
Data.Add("Foo", "again?");

If you serialize this you will get {"Foo":"baa,again?"}.

You can modify the converter to produce IDictionary<string, string[]> instead:

public static IDictionary<string, string[]> ToDictionary(
                                    this NameValueCollection source)
{
    return source.AllKeys.ToDictionary(k => k, k => source.GetValues(k));
}

So you can get serialized value like this: {"Foo":["baa","again?"]}.

Leave a Comment