convert NameValueCollection/Dictionary<string, object> to JSON string
2015-02-28 15:06
686 查看
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))
{
}
}
[/code]
{
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(); } } }
[/code]
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); } }
相关文章推荐
- value <html><head>java.lang. String connot be converted to jsonobject
- JsonHelper developed by using Newtonsoft.Json.NET, Deserialize to <T> object , XmlToJson/JsonToXml, QuoteName by using JToken Path.
- Type mismatch: cannot convert from Enumeration<String> to Enumeration<Object>
- Type mismatch: cannot convert from Enumeration<String> to Enumeration<Object>
- JSONException: Value of type java.lang.String cannot be converted to JSONObject
- Tuple<int, int> Dictionary<string, object>妙用
- java.lang.String cannot be convert to JSONObject
- Dictionary<string,object>性能之测试
- 泛型中字符串转集合,(T)object,typeOf(T),LIst<T> xxx<T>();c# stringtolist
- Value of type java.lang.String cannot be converted to JSONObject 异常
- Dictionary 和 List<Dictionary<string, object>>
- Value of type java.lang.String cannot be converted to JSONObject
- Spring 注解 hibernate 实体方法 <property name="packagesToScan" value="com.sise.domain"/>
- 简单封装Jackson,实现JSON String<->Java Object的Mapper.
- Convert string to JSONObject by net.sf.json library
- Json解析异常处理方式(JSONException: Value of type java.lang.String cannot be converted to JSONObject)
- NameValueCollection To Json 。
- java如何解析json字符串(List<Map<String,Object>成功的类型)
- json&jsonArray&gson&list&List<Map<String,Object>>&listview&adapter
- Spring 注解 hibernate 实体方法 <property name="packagesToScan" value="com.sise.domain"/>