NameValueCollection To Json 。
原文:http://stackoverflow.com/questions/7003740/how-convert-namevaluecollection-to-json-string
NameValueCollection 转换为 Json 的时候,只把它的Keys 数组 转换为Json ,忽略了 Value , 方法就是把 NameValueCollection 转换为 字典,再转为Json
自定义Json转换类:
public static class JsonHelper { public static string ToJson<T>(this T source) { if (source == null) return string.Empty; var nv = source as NameValueCollection; if (nv != null) { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); //执行序列化 return jsonSerializer.Serialize(nv.ToDictionary()); } else { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); //执行序列化 return jsonSerializer.Serialize(source); } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="str"></param> /// <returns></returns> public static T FromJson<T>(this string str) where T : new() { if (str.HasValue() == false) { return new T(); } else { string ss = str.Trim().Replace(Environment.NewLine, ""); if (ss.StartsWith("[") == false && ss.StartsWith("{") == false) { str = "{" + str + "}"; } } if (str[0] == '[') { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); return jsonSerializer.Deserialize<T>(str); } Type type = typeof(T); var nvType = typeof(NameValueCollection); if (type == nvType || type.IsSubclassOf(nvType)) { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); var dict = jsonSerializer.Deserialize<Dictionary<string, string>>(str); NameValueCollection nv = new NameValueCollection(); if (dict == null) return new T(); foreach (var item in dict) { nv[item.Key] = item.Value; } return (T)(object)nv; } else { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); return jsonSerializer.Deserialize<T>(str); } } public static T[] Json2Array<T>(this string str) { if (str.HasValue() == false) { return new T[0]; } else { string ss = str.Trim().Replace(Environment.NewLine, ""); if (ss.StartsWith("[") == false && ss.StartsWith("{") == false) { str = "{" + str + "}"; } } JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); return jsonSerializer.Deserialize<T[]>(str); } }
作者:NewSea 出处:http://newsea.cnblogs.com/
QQ,MSN:iamnewsea@hotmail.com 如无特别标记说明,均为NewSea原创,版权私有,翻载必纠。欢迎交流,转载,但要在页面明显位置给出原文连接。谢谢。 |