how to convert NameValueCollection to JSON string?

namevaluecollection to dictionary
json to namevaluecollection c#
namevaluecollection to string
dictionary to json c#
convert a dictionary to json string c#
convert map to json c#
namevaluecollection create
namevaluecollection to keyvaluepair

I tried:

  NameValueCollection Data = new NameValueCollection();
  Data.Add("foo","baa");
  string json = new JavaScriptSerializer().Serialize(Data);

it returns: ["foo"] I expected {"foo" : "baa"} How do I to do this?

NameValueCollection isn't an IDictionary, so the JavaScriptSerializer cannot serialize it as you expect directly. You'll need to first convert it into a dictionary, then serialize it.

Update: following questions regarding multiple values per key, the call to nvc[key] will simply return them separated by a comma, which may be ok. If not, one can always call GetValues and decide what to do with the values appropriately. Updated the code below to show one possible way.

public class StackOverflow_7003740
{
    static Dictionary<string, object> NvcToDictionary(NameValueCollection nvc, bool handleMultipleValuesPerKey)
    {
        var result = new Dictionary<string, object>();
        foreach (string key in nvc.Keys)
        {
            if (handleMultipleValuesPerKey)
            {
                string[] values = nvc.GetValues(key);
                if (values.Length == 1)
                {
                    result.Add(key, values[0]);
                }
                else
                {
                    result.Add(key, values);
                }
            }
            else
            {
                result.Add(key, nvc[key]);
            }
        }

        return result;
    }

    public static void Test()
    {
        NameValueCollection nvc = new NameValueCollection();
        nvc.Add("foo", "bar");
        nvc.Add("multiple", "first");
        nvc.Add("multiple", "second");

        foreach (var handleMultipleValuesPerKey in new bool[] { false, true })
        {
            if (handleMultipleValuesPerKey)
            {
                Console.WriteLine("Using special handling for multiple values per key");
            }
            var dict = NvcToDictionary(nvc, handleMultipleValuesPerKey);
            string json = new JavaScriptSerializer().Serialize(dict);
            Console.WriteLine(json);
            Console.WriteLine();
        }
    }
}

public static IDictionary<string, string[]> ToDictionary( this NameValueCollection source) { return source.AllKeys.ToDictionary(k => k, k => source.GetValues(k)); } For completeness' sake, and because the question continues to get asked (e.g. here), as long as you are using Json.NET or DataContractJsonSerializer (but not JavaScriptSerializer), you could use the adapter pattern and wrap the NameValueCollection in an IDictionary<string, string[]> adapter, and serialize that using any serializer that fully

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?"]}.

11. public static string JSONSerialize( this NameValueCollection _nvc). {. return JsonConvert.SerializeObject(_nvc.AllKeys.ToDictionary(k => k  questions/7003740/how-to-convert-namevaluecollection-to-json-string | Test your C# code online with .NET Fiddle code editor.

If your dictionary is not intended to contain many entries, you can use the class: System.Collections.Specialized.ListDictionary

Json.NET has excellent support for serializing and deserializing collections of objects. Add(p2); string json = JsonConvert.SerializeObject(products, Formatting  Re: Json and Dictionary<string, string> or NameValueCollection Oct 11, 2008 06:20 AM | Svante | LINK From the looks of it (I have no experience with JSon serialization as such, but from your example I can guess a bit about how the serializer works), you'll need an enumerable collection of objects or a single object with the appropriate properties.

String) { nameValueCollection.Add(key, reader.Value.ToString()); } } return nameValueCollection; } public override bool CanConvert(Type  How can I convert a Dictionary<string, string> to a NameValueCollection? The existing functionality of our project returns an old-fashioned NameValueCollection which I modify with LINQ. The result should be passed on as a NameValueCollection. I want to solve this in a generic way. Any hints?

Hi, How can I convert from a Dictionary or NameValueCollection into a Json string which can later go through the reverse process? I have tried  So, I created a HttpClient and am posting data using HttpClient.PostAsync (). HttpContent content = new FormUrlEncodedContent (post_parameters); where post_parameters is a list of Key value pairs List<KeyValuePair<string, string>> Problem is, when the HttpContent has a large value (an image converted to base64 to be transmitted) I get a URL is

NameValueCollection is used to store a collection of associated String keys and String values that can be accessed either with the key or with the index. How to convert json to NameValueCollection in C#. public static Dictionary<string, string> JSONToDIC(string json) { JavaScriptSerializer jss;

I have attache a function that would treat this string as you mentioned as the Request.QueryString method would the URL querystring in a web page. This function accepts the raw data as the first paramater and the variable desired as the second variable.

Comments
  • NameValueCollection could have multiple values per key, this does not address that issue.
  • This method will likely cause exceptions! The reason why NameValueCollection exists (and .NET doesn't use a dictionary sometimes) is to allow for multiple values per key. A dictionary requires one and only one key per value.
  • The method won't throw an exception. If there are multiple keys, nvc[key] would just return them joined by a , character. But for completeness sake, I updated the answer to be more explicit about it.
  • If the query string has not been made into a NameValueCollection then this works: stackoverflow.com/questions/12428947/…
  • DotNetFiddle: Multiple Keys on NameValueCollection dotnetfiddle.net/hnYwGn