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 ...
随机推荐
- Mysql 排序优化与索引使用(转)
为了优化SQL语句的排序性能,最好的情况是避免排序,合理利用索引是一个不错的方法.因为索引本身也是有序的,如果在需要排序的字段上面建立了合适的索引,那么就可以跳过排序的过程,提高SQL的查询速度.下面 ...
- linux 命令之系统活动报告sar
打开自己的CentOS,敲入“sar”,表示很失望: [root@localhost ~]# sar bash: sar: command not found 竟然没有安装,不过还好linux下安装还 ...
- Debian安装记录
Fedora着实让我伤心透了.前天和昨天搞了整整两天Fedora 20的安装,午睡也没有,晚上就睡了四个小时不到,几乎尝试了所有Fedora 20的桌面版本,全部出问题了!就因为我的笔记本显卡是ATI ...
- RDO部署openstack(2)
配置ML2和VXLAN 1. 安装和配置Neutron ML2 框架 (1) 安装在控制节点上(运行Neutron-server的节点) service neutron-server stop y ...
- JAVA获取当前时间加一天
01.获取当前时间 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return df.for ...
- 【Java安装】Centos6.8 安装Java1.6
安装java 1.6 Centos6.8安装完成后,一般都安装了java,为了安装java1.6,需要卸载系统自带的java,主要步骤: 先安装java1.6,目的:为了防止先卸载系统自带java时, ...
- bzoj2044: 三维导弹拦截
Description 一场战争正在A国与B国之间如火如荼的展开. B国凭借其强大的经济实力开发出了无数的远程攻击导弹,B国的领导人希望,通过这些导弹直接毁灭A国的指挥部,从而取得战斗的胜利!当然,A ...
- jquery form表单序列号
1.serialize()方法 格式:var data = $("form").serialize(); 功能:将表单内容序列化成一个字符串. 这样在ajax提交表单数据时,就不用 ...
- httpd安装
1.软件准备 http://apache.fayea.com/apache-mirror//apr/apr-1.5.1.tar.gz http://apache.fayea.com/apache-mi ...
- powerdesigner12.5 设置表字符集和存储引擎
powerdesigner12.5在做建模的时候发现没有找到哪儿设置表的字符集和存储引擎.于是研究了一番. 在菜单上方选择 Database => Edit Current DBMS 然后选 ...