如何NameValueCollection中转换成JSON字符串?字符串、NameValueCollection、JSON

由网友(世界很宽,孤独很满)分享简介:我想:NameValueCollection Data = new NameValueCollection();Data.Add("foo","baa");string json = new JavaScriptSerializer().Serialize(Data);返回: [富] 我预计 {富:咩} 我如何做到这...

我想:

  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 不是一个IDictionary,因此 JavaScriptSerializer ,你直接想到不能序列化。您需要先将其转换成一个字典,然后序列化。

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.

更新:对于每个键多个值以下几个问题,调用雷士照明[关键] 只会返回他们用逗号,分开这可能是好的。如果没有,你可以随时拨打的GetValues​​ ,并决定如何处理适当的值。更新了code以下,显示一种可能的方式。

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();
        }
    }
}
阅读全文

相关推荐

最新文章