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 ...
随机推荐
- Jfinal基础学习(一)
我负责的项目都是Jfinal的了,有必要写一些学习知识,记录下来. 1.PropKit.use("config.txt", "UTF-8"); PropKit ...
- java提供的默认list排序方法-转
1.java提供的默认list排序方法 主要代码: List<String> list = new ArrayList();list.add("刘媛媛"); list. ...
- hadoop(五): shell命令
hdfs dfs -cat URI : 查看文件内容 hdfs dfs -cat hdfs dfs -cat hdfs://mycluster/user/root/rcc1 hdfs dfs -cat ...
- UI设计的重要性--避免二义性的输入提示
昨天晚上发现了西安公路客运网上售票系统网站的密码找回系统存在安全漏洞,得出的结论是:密码找回页的漏洞: 1.用户名栏支持用户名.身份证.电话三种任意一种匹配.2.这一步是关键,密码找回问题提示栏居 ...
- 批处理安装APK
set adbpa=D:\Nexus6\ota51\ADBTool set apkpa=D:\WDJDownload\Apps %adbpa%\adb.exe install %apkpa%\CPU- ...
- noaman日志第一条:2015-1024;“Hello.World”
在南京的不知道第几个周末,一夜的煎熬终于活过来了.清早起来开通了自己的博客,第一条说说就记录开通博客这个事件.没有别的. 之后我会着重记录每天看书内容,以及所要编写的重要程序,一点一滴地积累希望能收获 ...
- IntelliJ IDEA设置自动导入包
IntelliJ IDEA可以自动优化导入包,但是有多个同名的类位于不同的包时,需要自己手动使用Alt + Enter进行导入. Settings→Editor→General→Auto Import ...
- bzoj4316: 小C的独立集
Description 图论小王子小C经常虐菜,特别是在图论方面,经常把小D虐得很惨很惨. 这不,小C让小D去求一个无向图的最大独立集,通俗地讲就是:在无向图中选出若干个点,这些点互相没有边连接,并使 ...
- svn 批量更新 bat脚本
由于有多个程序放在svn上管理,每天都要进入相应的目录进行svn 更新操作,现在写了一个简单的脚本进行批量自动更新. Code@echo off @echo ********************* ...
- Service代码示例
package com.homily.training.service; import android.app.Service; import android.content.Intent; impo ...