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

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);
    }
  }
时间: 2024-10-12 16:06:18

convert NameValueCollection/Dictionary<string, object> to JSON string的相关文章

Convert JS object to JSON string

Modern browsers (IE8, FF3, Chrome etc.) have native JSON support built in (Same API as with JSON2). So as long you're not dealing with IE6/7 you can do it just as easily as that: var j={"name":"binchen"}; JSON.stringify(j); // '{"

Dictionary&lt;string, object&gt;

Dictionary<string, object> dcic = JsonHelper.DataRowFromJSON(resultdepth); foreach (var depthkey in dcic.Keys) { if (depthkey.Contains("data")) { Dictionary<string, object> Ddata = (Dictionary<string, object>)dcic["data&qu

通过递归将list&lt;Map&lt;String,Object&gt;&gt;类型的数据转换为tree组件可识别的json数据

public static JSONObject getDeptTree(List<Map<String,Object>> list,String id) throws JSONException{ JSONObject json=new JSONObject(); JSONArray jsons=new JSONArray();//children数组 for (Map<String, Object> map : list) { String id=map.get(&

FastJSON 简介及其Map/JSON/String 互转

在日志解析,前后端数据传输交互中,经常会遇到 String 与 map.json.xml 等格式相互转换与解析的场景,其中 json 基本成为了跨语言.跨前后端的事实上的标准数据交互格式.应该来说各个语言中 解析 json 的库都一大片(具体 json 格式与三方库的介绍请见:http://www.json.org/json-zh.html),比如 python 都集成在了内置库中,成为标准 API,今天我们要聊的是 java 中如何方便的使用 json 格式. 从上面的链接介绍中我们可以看到,

String转成JSON的实现

String转成JSON 这个依赖很重要,我们将围绕fastjson中的JSONObject这个类来谈转换 <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.15</version> </dependency> String转成JSON String json = "{\

今天学会了对List&lt;Map&lt;String,Object&gt;&gt;的排序

Collections.sort(dyList, new Comparator<Map<String, Object>>() { public int compare(Map<String, Object> arg0, Map<String, Object> arg1) { int map1value=0; int map2value=0; if(arg0.get("getlicenseDate")!=null&&!arg

List&lt;map&lt;String,Object&gt;&gt;

List<Map<String, Object>> list = sendService.getApproveMsgToMap(); //第一种 //遍历map for (Map<String, Object> m : list) { for (String k : m.keySet()) { System.out.println(k + " : " + m.get(k)); } } //第二种 for (int i = 0; i < list

对List&lt;Map&lt;String,Object&gt;&gt; 进行排序

1 package lltse.base.collectiondemo; 2 3 import java.util.ArrayList; 4 import java.util.Collections; 5 import java.util.Comparator; 6 import java.util.HashMap; 7 import java.util.List; 8 import java.util.Map; 9 import java.util.Random; 10 11 12 publi

将Map&lt;String, List&lt;Map&lt;String,Object&gt;&gt;&gt;进行排序

首先我贴上我的代码,刚开始我也不知道怎么排序还写了一些方法,最后请教群里的大神解决了 public Map<String, List<Map<String,Object>>> getGrowList(String id){ List<Map<String, Object>> growList = mentDao.getGrowList(id); SortedMap<String, List<Map<String,Object&g