Serialize Deserialize NameValueCollection

Don’t ask me why one cannot Serialize/Deserialize a NameValueCollection, but the workaround for the same is based on conversion to dictionary. I ended up writing extension methods to NameValueCollection for serializing and deserializing the collection.

public static string JSONSerialize(this NameValueCollection _nvc)
return JsonConvert.SerializeObject(_nvc.AllKeys.ToDictionary(k => k, k =>_nvc.GetValues(k)));
public static void JSONDeserialize(this NameValueCollection _nvc,string _serializedString)
var deserializedobject = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(_serializedString);
foreach (var strCol in deserializedobject.Values)
foreach (var str in strCol)
_nvc.Add(deserializedobject.FirstOrDefault(x => x.Value.Contains(str)).Key, str);

2 thoughts on “Serialize Deserialize NameValueCollection

  1. This is useful but has some flawed logic – JSONDeserialize doesn’t work if a value for one key-value pair is a substring of a value in a different key-value pair. Try this for JSONDeserialize instead:

    public static void JSONDeserialize(this NameValueCollection _nvc, string _serializedString)
    var deserializedobject = JsonConvert.DeserializeObject<Dictionary>(_serializedString);

    foreach (var kvp in deserializedobject)
    foreach (var str in kvp.Value)
    _nvc.Add(kvp.Key, str);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s