asp.net 2.0里也可以用JSON的使用方法
更新時間:2010年03月30日 12:49:56 作者:
本人找到一份,可以在asp.net2.0里實現(xiàn)JSON方式傳送數(shù)據(jù)的方法。但是原方法,不能在數(shù)據(jù)中帶有{、}、[、]、"等,所以我做特意做了轉(zhuǎn)意。
全部代碼如下。
/// <summary>
/// JSON解析類
/// </summary>
public static class JSONConvert
{
#region 全局變量
private static JSONObject _json = new JSONObject();//寄存器
private static readonly string _SEMICOLON = "@semicolon";//分號轉(zhuǎn)義符
private static readonly string _COMMA = "@comma"; //逗號轉(zhuǎn)義符
#endregion
#region 字符串轉(zhuǎn)義
/// <summary>
/// 字符串轉(zhuǎn)義,將雙引號內(nèi)的:和,分別轉(zhuǎn)成_SEMICOLON和_COMMA
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static string StrEncode(string text)
{
MatchCollection matches = Regex.Matches(text, "\\\"[^\\\"]+\\\"");
foreach (Match match in matches)
{
text = text.Replace(match.Value, match.Value.Replace(":", _SEMICOLON).Replace(",", _COMMA));
}
return text;
}
/// <summary>
/// 字符串轉(zhuǎn)義,將_SEMICOLON和_COMMA分別轉(zhuǎn)成:和,
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static string StrDecode(string text)
{
return text.Replace(_SEMICOLON, ":").Replace(_COMMA, ",");
}
#endregion
#region JSON最小單元解析
/// <summary>
/// 最小對象轉(zhuǎn)為JSONObject
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static JSONObject DeserializeSingletonObject(string text)
{
JSONObject jsonObject = new JSONObject();
MatchCollection matches = Regex.Matches(text, "(\\\"(?<key>[^\\\"]+)\\\":\\\"(?<value>[^,\\\"]+)\\\")|(\\\"(?<key>[^\\\"]+)\\\":(?<value>[^,\\\"\\}]+))");
foreach (Match match in matches)
{
string value = match.Groups["value"].Value;
jsonObject.Add(match.Groups["key"].Value, _json.ContainsKey(value) ? _json[value] : StrDecode(value));
}
return jsonObject;
}
/// <summary>
/// 最小數(shù)組轉(zhuǎn)為JSONArray
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static JSONArray DeserializeSingletonArray(string text)
{
JSONArray jsonArray = new JSONArray();
MatchCollection matches = Regex.Matches(text, "(\\\"(?<value>[^,\\\"]+)\")|(?<value>[^,\\[\\]]+)");
foreach (Match match in matches)
{
string value = match.Groups["value"].Value;
jsonArray.Add(_json.ContainsKey(value) ? _json[value] : StrDecode(value));
}
return jsonArray;
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static string Deserialize(string text)
{
text = StrEncode(text);//轉(zhuǎn)義;和,
int count = 0;
string key = string.Empty;
string pattern = "(\\{[^\\[\\]\\{\\}]+\\})|(\\[[^\\[\\]\\{\\}]+\\])";
while (Regex.IsMatch(text, pattern))
{
MatchCollection matches = Regex.Matches(text, pattern);
foreach (Match match in matches)
{
key = "___key" + count + "___";
if (match.Value.Substring(0, 1) == "{")
_json.Add(key, DeserializeSingletonObject(match.Value));
else
_json.Add(key, DeserializeSingletonArray(match.Value));
text = text.Replace(match.Value, key);
count++;
}
}
return text;
}
#endregion
#region 公共接口
/// <summary>
/// 序列化JSONObject對象
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static JSONObject DeserializeObject(string text)
{
_json = new JSONObject();
return _json[Deserialize(text)] as JSONObject;
}
/// <summary>
/// 序列化JSONArray對象
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static JSONArray DeserializeArray(string text)
{
_json = new JSONObject();
return _json[Deserialize(text)] as JSONArray;
}
/// <summary>
/// 反序列化JSONObject對象
/// </summary>
/// <param name="jsonObject"></param>
/// <returns></returns>
public static string SerializeObject(JSONObject jsonObject)
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
foreach (KeyValuePair<string, object> kvp in jsonObject)
{
if (kvp.Value is JSONObject)
{
sb.Append(string.Format("\"{0}\":{1},", kvp.Key, SerializeObject((JSONObject)kvp.Value)));
}
else if (kvp.Value is JSONArray)
{
sb.Append(string.Format("\"{0}\":{1},", kvp.Key, SerializeArray((JSONArray)kvp.Value)));
}
else if (kvp.Value is String)
{
sb.Append(string.Format("\"{0}\":\"{1}\",", kvp.Key, kvp.Value));
}
else
{
sb.Append(string.Format("\"{0}\":\"{1}\",", kvp.Key, ""));
}
}
if (sb.Length > 1)
sb.Remove(sb.Length - 1, 1);
sb.Append("}");
return sb.ToString();
}
/// <summary>
/// 反序列化JSONArray對象
/// </summary>
/// <param name="jsonArray"></param>
/// <returns></returns>
public static string SerializeArray(JSONArray jsonArray)
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
for (int i = 0; i < jsonArray.Count; i++)
{
if (jsonArray[i] is JSONObject)
{
sb.Append(string.Format("{0},", SerializeObject((JSONObject)jsonArray[i])));
}
else if (jsonArray[i] is JSONArray)
{
sb.Append(string.Format("{0},", SerializeArray((JSONArray)jsonArray[i])));
}
else if (jsonArray[i] is String)
{
sb.Append(string.Format("\"{0}\",", jsonArray[i]));
}
else
{
sb.Append(string.Format("\"{0}\",", ""));
}
}
if (sb.Length > 1)
sb.Remove(sb.Length - 1, 1);
sb.Append("]");
return sb.ToString();
}
#endregion
}
/// <summary>
/// 取出JSON對象類
/// </summary>
public class JSONObject : Dictionary<string, object>
{
public new void Add(string key, object value)
{
System.Type t = value.GetType();
if (t.Name == "String")
{
value = JsonEncode.StrEncodeForDeserialize(value.ToString());
}
base.Add(key, value);
}
}
/// <summary>
/// 取出JSON數(shù)組類
/// </summary>
public class JSONArray : List<object>
{
public new void Add(object item)
{
System.Type t = item.GetType();
if (t.Name == "String")
{
item = JsonEncode.StrEncodeForDeserialize(item.ToString());
}
base.Add(item);
}
}
/// <summary>
/// 字符串轉(zhuǎn)義,將"{"、"}"、"""
/// </summary>
public class JsonEncode
{
public static readonly string _LEFTBRACES = "@leftbraces";//"{"轉(zhuǎn)義符
public static readonly string _RIGHTBRACES = "@rightbraces";//"}"轉(zhuǎn)義符
public static readonly string _LEFTBRACKETS = "@leftbrackets";//"["轉(zhuǎn)義符
public static readonly string _RIGHTBRACKETS = "@rightbrackets";//"]"轉(zhuǎn)義符
public static readonly string _DOUBLEQUOTATIONMARKS = "@doubleQuotationMarks";//"""轉(zhuǎn)義符
#region 字符串轉(zhuǎn)義
/// <summary>
/// 字符串轉(zhuǎn)義,將"{"、"}"、""",分別轉(zhuǎn)換_LEFTBRACES、_RIGHTBRACES、_DOUBLEQUOTATIONMARKS
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string StrEncodeForDeserialize(string text)
{
return text
.Replace("{", _LEFTBRACES)
.Replace("}", _RIGHTBRACES)
.Replace("[", _LEFTBRACKETS)
.Replace("]", _RIGHTBRACKETS)
.Replace("\"", _DOUBLEQUOTATIONMARKS);
}
/// <summary>
/// 字符串轉(zhuǎn)義,將_LEFTBRACES、_RIGHTBRACES、_DOUBLEQUOTATIONMARKS,分別轉(zhuǎn)換"{"、"}"、"""
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string StrDecodeForDeserialize(string text)
{
return text.Replace(_LEFTBRACES, "{")
.Replace(_RIGHTBRACES, "}")
.Replace(_LEFTBRACKETS, "[")
.Replace(_RIGHTBRACKETS, "]")
.Replace(_DOUBLEQUOTATIONMARKS, "\"");
}
#endregion
}
最后要說的,就是比較馬煩的是,現(xiàn)在要取JSON里的值要用到下面的方法
this.Label2.Text = JsonEncode.StrDecodeForDeserialize(json["domain"].ToString());
this.Label2.Text = JsonEncode.StrDecodeForDeserialize(((JSONArray)json["years"])[4].ToString());
復制代碼 代碼如下:
/// <summary>
/// JSON解析類
/// </summary>
public static class JSONConvert
{
#region 全局變量
private static JSONObject _json = new JSONObject();//寄存器
private static readonly string _SEMICOLON = "@semicolon";//分號轉(zhuǎn)義符
private static readonly string _COMMA = "@comma"; //逗號轉(zhuǎn)義符
#endregion
#region 字符串轉(zhuǎn)義
/// <summary>
/// 字符串轉(zhuǎn)義,將雙引號內(nèi)的:和,分別轉(zhuǎn)成_SEMICOLON和_COMMA
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static string StrEncode(string text)
{
MatchCollection matches = Regex.Matches(text, "\\\"[^\\\"]+\\\"");
foreach (Match match in matches)
{
text = text.Replace(match.Value, match.Value.Replace(":", _SEMICOLON).Replace(",", _COMMA));
}
return text;
}
/// <summary>
/// 字符串轉(zhuǎn)義,將_SEMICOLON和_COMMA分別轉(zhuǎn)成:和,
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static string StrDecode(string text)
{
return text.Replace(_SEMICOLON, ":").Replace(_COMMA, ",");
}
#endregion
#region JSON最小單元解析
/// <summary>
/// 最小對象轉(zhuǎn)為JSONObject
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static JSONObject DeserializeSingletonObject(string text)
{
JSONObject jsonObject = new JSONObject();
MatchCollection matches = Regex.Matches(text, "(\\\"(?<key>[^\\\"]+)\\\":\\\"(?<value>[^,\\\"]+)\\\")|(\\\"(?<key>[^\\\"]+)\\\":(?<value>[^,\\\"\\}]+))");
foreach (Match match in matches)
{
string value = match.Groups["value"].Value;
jsonObject.Add(match.Groups["key"].Value, _json.ContainsKey(value) ? _json[value] : StrDecode(value));
}
return jsonObject;
}
/// <summary>
/// 最小數(shù)組轉(zhuǎn)為JSONArray
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static JSONArray DeserializeSingletonArray(string text)
{
JSONArray jsonArray = new JSONArray();
MatchCollection matches = Regex.Matches(text, "(\\\"(?<value>[^,\\\"]+)\")|(?<value>[^,\\[\\]]+)");
foreach (Match match in matches)
{
string value = match.Groups["value"].Value;
jsonArray.Add(_json.ContainsKey(value) ? _json[value] : StrDecode(value));
}
return jsonArray;
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static string Deserialize(string text)
{
text = StrEncode(text);//轉(zhuǎn)義;和,
int count = 0;
string key = string.Empty;
string pattern = "(\\{[^\\[\\]\\{\\}]+\\})|(\\[[^\\[\\]\\{\\}]+\\])";
while (Regex.IsMatch(text, pattern))
{
MatchCollection matches = Regex.Matches(text, pattern);
foreach (Match match in matches)
{
key = "___key" + count + "___";
if (match.Value.Substring(0, 1) == "{")
_json.Add(key, DeserializeSingletonObject(match.Value));
else
_json.Add(key, DeserializeSingletonArray(match.Value));
text = text.Replace(match.Value, key);
count++;
}
}
return text;
}
#endregion
#region 公共接口
/// <summary>
/// 序列化JSONObject對象
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static JSONObject DeserializeObject(string text)
{
_json = new JSONObject();
return _json[Deserialize(text)] as JSONObject;
}
/// <summary>
/// 序列化JSONArray對象
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static JSONArray DeserializeArray(string text)
{
_json = new JSONObject();
return _json[Deserialize(text)] as JSONArray;
}
/// <summary>
/// 反序列化JSONObject對象
/// </summary>
/// <param name="jsonObject"></param>
/// <returns></returns>
public static string SerializeObject(JSONObject jsonObject)
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
foreach (KeyValuePair<string, object> kvp in jsonObject)
{
if (kvp.Value is JSONObject)
{
sb.Append(string.Format("\"{0}\":{1},", kvp.Key, SerializeObject((JSONObject)kvp.Value)));
}
else if (kvp.Value is JSONArray)
{
sb.Append(string.Format("\"{0}\":{1},", kvp.Key, SerializeArray((JSONArray)kvp.Value)));
}
else if (kvp.Value is String)
{
sb.Append(string.Format("\"{0}\":\"{1}\",", kvp.Key, kvp.Value));
}
else
{
sb.Append(string.Format("\"{0}\":\"{1}\",", kvp.Key, ""));
}
}
if (sb.Length > 1)
sb.Remove(sb.Length - 1, 1);
sb.Append("}");
return sb.ToString();
}
/// <summary>
/// 反序列化JSONArray對象
/// </summary>
/// <param name="jsonArray"></param>
/// <returns></returns>
public static string SerializeArray(JSONArray jsonArray)
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
for (int i = 0; i < jsonArray.Count; i++)
{
if (jsonArray[i] is JSONObject)
{
sb.Append(string.Format("{0},", SerializeObject((JSONObject)jsonArray[i])));
}
else if (jsonArray[i] is JSONArray)
{
sb.Append(string.Format("{0},", SerializeArray((JSONArray)jsonArray[i])));
}
else if (jsonArray[i] is String)
{
sb.Append(string.Format("\"{0}\",", jsonArray[i]));
}
else
{
sb.Append(string.Format("\"{0}\",", ""));
}
}
if (sb.Length > 1)
sb.Remove(sb.Length - 1, 1);
sb.Append("]");
return sb.ToString();
}
#endregion
}
/// <summary>
/// 取出JSON對象類
/// </summary>
public class JSONObject : Dictionary<string, object>
{
public new void Add(string key, object value)
{
System.Type t = value.GetType();
if (t.Name == "String")
{
value = JsonEncode.StrEncodeForDeserialize(value.ToString());
}
base.Add(key, value);
}
}
/// <summary>
/// 取出JSON數(shù)組類
/// </summary>
public class JSONArray : List<object>
{
public new void Add(object item)
{
System.Type t = item.GetType();
if (t.Name == "String")
{
item = JsonEncode.StrEncodeForDeserialize(item.ToString());
}
base.Add(item);
}
}
/// <summary>
/// 字符串轉(zhuǎn)義,將"{"、"}"、"""
/// </summary>
public class JsonEncode
{
public static readonly string _LEFTBRACES = "@leftbraces";//"{"轉(zhuǎn)義符
public static readonly string _RIGHTBRACES = "@rightbraces";//"}"轉(zhuǎn)義符
public static readonly string _LEFTBRACKETS = "@leftbrackets";//"["轉(zhuǎn)義符
public static readonly string _RIGHTBRACKETS = "@rightbrackets";//"]"轉(zhuǎn)義符
public static readonly string _DOUBLEQUOTATIONMARKS = "@doubleQuotationMarks";//"""轉(zhuǎn)義符
#region 字符串轉(zhuǎn)義
/// <summary>
/// 字符串轉(zhuǎn)義,將"{"、"}"、""",分別轉(zhuǎn)換_LEFTBRACES、_RIGHTBRACES、_DOUBLEQUOTATIONMARKS
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string StrEncodeForDeserialize(string text)
{
return text
.Replace("{", _LEFTBRACES)
.Replace("}", _RIGHTBRACES)
.Replace("[", _LEFTBRACKETS)
.Replace("]", _RIGHTBRACKETS)
.Replace("\"", _DOUBLEQUOTATIONMARKS);
}
/// <summary>
/// 字符串轉(zhuǎn)義,將_LEFTBRACES、_RIGHTBRACES、_DOUBLEQUOTATIONMARKS,分別轉(zhuǎn)換"{"、"}"、"""
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string StrDecodeForDeserialize(string text)
{
return text.Replace(_LEFTBRACES, "{")
.Replace(_RIGHTBRACES, "}")
.Replace(_LEFTBRACKETS, "[")
.Replace(_RIGHTBRACKETS, "]")
.Replace(_DOUBLEQUOTATIONMARKS, "\"");
}
#endregion
}
最后要說的,就是比較馬煩的是,現(xiàn)在要取JSON里的值要用到下面的方法
復制代碼 代碼如下:
this.Label2.Text = JsonEncode.StrDecodeForDeserialize(json["domain"].ToString());
this.Label2.Text = JsonEncode.StrDecodeForDeserialize(((JSONArray)json["years"])[4].ToString());
您可能感興趣的文章:
- 使用jQuery向asp.net Mvc傳遞復雜json數(shù)據(jù)-ModelBinder篇
- 使用ASP.NET一般處理程序或WebService返回JSON的實現(xiàn)代碼
- asp.net(C#)解析Json的類代碼
- asp.net JSONHelper JSON幫助類
- Jquery 組合form元素為json格式,asp.net反序列化
- asp.net+jquery Jsonp使用方法
- jQuery asp.net 用json格式返回自定義對象
- Jquery中g(shù)etJSON在asp.net中的使用說明
- asp.net中各種類型的JSON格式化
- ASP.NET自帶對象JSON字符串與實體類的轉(zhuǎn)換
相關(guān)文章
asp.net頁面master頁面與ascx用戶控件傳值的問題
aspx 頁面,master頁面與ascx用戶控件傳值的問題2010-03-03把aspx頁面?zhèn)窝b成靜態(tài)html格式的實現(xiàn)代碼
把aspx頁面?zhèn)窝b成靜態(tài)html格式的實現(xiàn)代碼,主要是利于搜索引擎的收錄。2011-10-10.Net語言Smobiler開發(fā)之如何仿微信朋友圈的消息樣式
這篇文章主要介紹了.Net語言Smobiler開發(fā)平臺如何仿微信朋友圈的消息樣式?本文為大家揭曉答案2016-09-09詳解將ASP.NET Core應用程序部署至生產(chǎn)環(huán)境中(CentOS7)
這篇文章主要介紹了詳解將ASP.NET Core應用程序部署至生產(chǎn)環(huán)境中(CentOS7),具有一定的參考價值,有需要的可以了解一下。2016-12-12vs.net 2010 擴展插件小結(jié) 提高編程效率
本文價紹了幾款Visual Studio提供的插件,提高我們的編程效率。2011-03-03Asp.Net Core利用文件監(jiān)視進行快速測試開發(fā)詳解
這篇文章主要給大家介紹了關(guān)于Asp.Net Core利用文件監(jiān)視進行快速測試開發(fā)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-12-12