convert NameValueCollection/Dictionary<string, object> to JSON string

來源:互聯網
上載者:User

標籤:

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);    }  }

convert NameValueCollection/Dictionary<string, object> to JSON string

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.