how to convert NameValueCollection to JSON string?

后端 未结 4 650
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 10:38

I tried:

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


        
4条回答
  •  迷失自我
    2020-11-28 10:57

    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 NvcToDictionary(NameValueCollection nvc, bool handleMultipleValuesPerKey)
        {
            var result = new Dictionary();
            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();
            }
        }
    }
    

提交回复
热议问题