convert NameValueCollection/Dictionary<string, object> 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);
}
}
convert NameValueCollection/Dictionary<string, object> to JSON string的更多相关文章
- List<Map<String, Object>> 与 json 互转
近期做指纹识别,需要用到缓存文件,数据量并不大,用redis不合适,所以用到了txt文件. 思路是 1.定时查询指纹,存到txt缓存文件中. 2.新增或删除指纹时,查询指纹,存到txt缓存文 ...
- c# Dictionary<string, object> 转JSON字符串
JavaScriptSerializer jss = new JavaScriptSerializer(); Dictionary<string, object> dict = new D ...
- <<< List<HashMap<String, Object>> 及 HashMap<String, Object> 的用法
//(赋值)最简单的一种hashMap赋值方式 List<HashMap<String, Object>> aMap= new ArrayList<HashMap< ...
- Convert JS object to JSON string
Modern browsers (IE8, FF3, Chrome etc.) have native JSON support built in (Same API as with JSON2). ...
- Jackson将json string转为Object,org.json读取json数组
从json文件读取json string或者自定义json string,将其转为object.下面采用的object为map,根据map读取json的某个数据,可以读取第一级的数据name,后来发现 ...
- Dictionary<string, object>
Dictionary<string, object> dcic = JsonHelper.DataRowFromJSON(resultdepth); foreach (var depthk ...
- FastJSON 简介及其Map/JSON/String 互转
在日志解析,前后端数据传输交互中,经常会遇到 String 与 map.json.xml 等格式相互转换与解析的场景,其中 json 基本成为了跨语言.跨前后端的事实上的标准数据交互格式.应该来说各个 ...
- String, JSONArray , JSONObject ,Map<String, Object> 与对象
String pic = "[{\"picServiceUrl\": \"0f4bb44afb2e48d48b786d3bbdeec283/20180408/6 ...
- String 转 List<Map<String, Object>>
public static List<Map<String, Object>> toListMap(String json){ List<Object> list ...
随机推荐
- [linux] cp: omitting directory `XXX'问题解决
在linux系统中复制文件夹时提示如下: cp: omitting directory `foldera/' 其中foldera是我要复制的文件夹名,出现该警告的原因是因为foldera目录下还存在目 ...
- 微博一键分享主要通过对指定 URL 添加各种参数来实现;
微博一键分享主要通过对指定 URL 添加各种参数来实现:也可以用在线生成器自动生成. 示例: 搜狐微博一键分享 URL,只需三个参数: http://t.sohu.com/third/post.jsp ...
- webstorm配置nodejs,bower,git,github
一,配置nodejs第一大步,首先安装nodejs,安装nodejs的时候,我们需要把所有的组建勾选上,然后选择add to path,这一步会自动帮我们配置环境变量,安装完成后,打开cmd,输入no ...
- RESRful API 和 HTTP状态码
一.RESRful API: GET(SELECT):从服务器取出资源(一项或多项). POST(CREATE):在服务器新建一个资源. PUT(UPDATE):在服务器更新资源(客户端提供改变后的完 ...
- 借助LVS+Keepalived通过DR模式实现负载均衡
1.测试环境4台server,全部初始化一下,该关的关了 # vim /etc/hosts 192.168.1.101 lvs-master DIP 192.168.1.102 lvs-slave D ...
- ResultSet的getInt(),getString()方法
数据库tt的examstudent数据表如下: 在MySQL中执行查询语句如下: ResultSet rs = null; String sql="SELECT flow_id,Typ ...
- 【原】C# decimal字符串转成整数
第一种方法: string na="1000.53"; int a=int.Parse(na.Substring(0,na.IndexOf('.')));//返回值a=1000 第 ...
- DBA_Oracle DBA常用表汇总(概念)
2014-06-20 Created By BaoXinjian
- cf111D Petya and Coloring 组合数学,二项式反演
http://codeforces.com/contest/111/problem/D Little Petya loves counting. He wants to count the numbe ...
- [MySQL] 两个优化数据库表的简单方法--18.3
这里介绍两个简单的优化MySQL数据库表的方法 一.定期分析表和检查表 1.分析表语法如下: alalyze [local|no_write_to_binlog] table table_name1[ ...