convert NameValueCollection/Dictionary to JSON string

 

public static class WebExtension
{
public static T Decode<T>(this RequestBase res)
{
Type type = res.GetType();

// For each property of this object, html decode it if it is of type string
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
//if (propertyInfo.Name.ToLower() == "api_timestamp" || propertyInfo.Name.ToLower() == "api_signature" || propertyInfo.Name.ToLower() == "api_version")
//{
// continue;
//}
var prop = propertyInfo.GetValue(res, null);
if (prop != null && prop.GetType() == typeof(string))
{
propertyInfo.SetValue(res, HttpUtility.UrlDecode((string)prop), null);
}
}
T result = (T)Activator.CreateInstance(type);
return result;
}
}

 

var col=HttpContext.Current.Request.Form;
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (var key in col.AllKeys)
{
//dict.Add(k, col[k]);
string[] values = col.GetValues(key);
if (values.Length == 1)
{
dict.Add(key, values[0]);
}
else
{
dict.Add(key, values);
}
}
var json = JsonConvert.SerializeObject(dict);

foreach (var key in col.AllKeys)
{
foreach (var val in col.GetValues(key))
{

}
}

 

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 class UrlStatus

    {

      public int Status { get; set; }

      public string Url { get; set; }

    }





    [Test]

    public void GenericDictionaryObject()

    {

      Dictionary<string, object> collection = new Dictionary<string, object>()

        {

          {"First", new UrlStatus{ Status = 404, Url = @"http://www.bing.com"}},

          {"Second", new UrlStatus{Status = 400, Url = @"http://www.google.com"}},

          {"List", new List<UrlStatus>

            {

              new UrlStatus {Status = 300, Url = @"http://www.yahoo.com"},

              new UrlStatus {Status = 200, Url = @"http://www.askjeeves.com"}

            }

          }

        };



      string json = JsonConvert.SerializeObject(collection, Formatting.Indented, new JsonSerializerSettings

      {

        TypeNameHandling = TypeNameHandling.All,

        TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple

      });



      Assert.AreEqual(@"{

  ""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"",

  ""First"": {

    ""$type"": ""Newtonsoft.Json.Tests.Serialization.TypeNameHandlingTests+UrlStatus, Newtonsoft.Json.Tests"",

    ""Status"": 404,

    ""Url"": ""http://www.bing.com""

  },

  ""Second"": {

    ""$type"": ""Newtonsoft.Json.Tests.Serialization.TypeNameHandlingTests+UrlStatus, Newtonsoft.Json.Tests"",

    ""Status"": 400,

    ""Url"": ""http://www.google.com""

  },

  ""List"": {

    ""$type"": ""System.Collections.Generic.List`1[[Newtonsoft.Json.Tests.Serialization.TypeNameHandlingTests+UrlStatus, Newtonsoft.Json.Tests]], mscorlib"",

    ""$values"": [

      {

        ""$type"": ""Newtonsoft.Json.Tests.Serialization.TypeNameHandlingTests+UrlStatus, Newtonsoft.Json.Tests"",

        ""Status"": 300,

        ""Url"": ""http://www.yahoo.com""

      },

      {

        ""$type"": ""Newtonsoft.Json.Tests.Serialization.TypeNameHandlingTests+UrlStatus, Newtonsoft.Json.Tests"",

        ""Status"": 200,

        ""Url"": ""http://www.askjeeves.com""

      }

    ]

  }

}", json);



      object c = JsonConvert.DeserializeObject(json, new JsonSerializerSettings

      {

        TypeNameHandling = TypeNameHandling.All,

        TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple

      });



      Assert.IsInstanceOfType(typeof(Dictionary<string, object>), c);



      Dictionary<string, object> newCollection = (Dictionary<string, object>)c;

      Assert.AreEqual(3, newCollection.Count);

      Assert.AreEqual(@"http://www.bing.com", ((UrlStatus)newCollection["First"]).Url);



      List<UrlStatus> statues = (List<UrlStatus>) newCollection["List"];

      Assert.AreEqual(2, statues.Count);

    }

  }

你可能感兴趣的:(Collection)