how to convert NameValueCollection to JSON string?

后端 未结 4 657
佛祖请我去吃肉
佛祖请我去吃肉 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:47

    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 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 instead:

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

提交回复
热议问题