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

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

  1. List<Map<String, Object>> 与 json 互转

    近期做指纹识别,需要用到缓存文件,数据量并不大,用redis不合适,所以用到了txt文件. 思路是 1.定时查询指纹,存到txt缓存文件中.      2.新增或删除指纹时,查询指纹,存到txt缓存文 ...

  2. c# Dictionary<string, object> 转JSON字符串

    JavaScriptSerializer jss = new JavaScriptSerializer(); Dictionary<string, object> dict = new D ...

  3. <<< List<HashMap<String, Object>> 及 HashMap<String, Object> 的用法

    //(赋值)最简单的一种hashMap赋值方式 List<HashMap<String, Object>> aMap= new ArrayList<HashMap< ...

  4. Convert JS object to JSON string

    Modern browsers (IE8, FF3, Chrome etc.) have native JSON support built in (Same API as with JSON2). ...

  5. Jackson将json string转为Object,org.json读取json数组

    从json文件读取json string或者自定义json string,将其转为object.下面采用的object为map,根据map读取json的某个数据,可以读取第一级的数据name,后来发现 ...

  6. Dictionary<string, object>

    Dictionary<string, object> dcic = JsonHelper.DataRowFromJSON(resultdepth); foreach (var depthk ...

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

    在日志解析,前后端数据传输交互中,经常会遇到 String 与 map.json.xml 等格式相互转换与解析的场景,其中 json 基本成为了跨语言.跨前后端的事实上的标准数据交互格式.应该来说各个 ...

  8. String, JSONArray , JSONObject ,Map<String, Object> 与对象

    String pic = "[{\"picServiceUrl\": \"0f4bb44afb2e48d48b786d3bbdeec283/20180408/6 ...

  9. String 转 List<Map<String, Object>>

    public static List<Map<String, Object>> toListMap(String json){ List<Object> list ...

随机推荐

  1. HiveQ与传统SQL差异

    1.   hive内连接支持什么格式? • SQL中对两表内联可以写成:        select * from dual a,dual b where a.key = b.key; 或者: SEL ...

  2. 解决方案:将已存在的项目 添加到 tfs解决方案中的时候 出现:新项目不能成功加入源码控制

    遇到此问题 可能是因为你的 解决方案文件 没有正确与 tfs服务器绑定导致的 解决方式是: 在打开任意一个源码文件的时候,打开 vs2013的 文件>> Go to File->So ...

  3. 【VNC】Ubuntu14.04LTS下安装VNC View

    # apt-get install tightvncserver vnc4server gnome-panel gnome-settings-daemon metacity nautilus gnom ...

  4. 同名域中计算机之间RDP问题

    今天遇到一个奇葩问题 server1 在domain1中 server2 在domain2中 domain1 和domain2的名字一样,然后从server1去RDP到server2,你是无论如何都无 ...

  5. C语言每日一题之No.4

    这几天老大也没安排我什么项目,于是想正好趁着空补C.当然,是利用晚上加班时间,白天正常上班时间还是学习公司的平台. 今儿个突然弱弱的感觉到在公司补C是件很低级的事情,哪怕是在加班时间都会被喷,因为大家 ...

  6. Tomcat服务器搭建

    一.JDK环境搭建 二.tomcat下载安装 三.tomcat服务启动 cmd> net start  tomcat8 四.查看tomcat服务器启动情况: http://localhost:8 ...

  7. ArrayList源码

      1.首先看对ArrayList的定义:   public class ArrayList<E> extends AbstractList<E> implements Lis ...

  8. python (18)在linux中如何实现定时发送邮件

    最近要用到,定时发送邮件功能: 如何定时,当然要用到linux中crontab了 如下的代码能够定时发送邮件 #!/usr/bin/env python # -*- coding=utf-8 -*- ...

  9. sql异常

    表结构 Id int UncheckedTitle nvarchar(50) CheckedValue nvarchar(1000) CheckedRemark nvarchar(1000) Chec ...

  10. filter的执行顺序

    一直没有仔细去研究下filter ,最近系统的测试了下: 先看代码吧 FirstFilter.java ================== package com.test.filter; impo ...