asp.net 2.0裡也可以用JSON的使用方法

來源:互聯網
上載者:User

全部代碼如下。 複製代碼 代碼如下:/// <summary>
/// JSON解析類
/// </summary>
public static class JSONConvert
{
#region 全域變數

private static JSONObject _json = new JSONObject();//寄存器
private static readonly string _SEMICOLON = "@semicolon";//分號轉義符
private static readonly string _COMMA = "@comma"; //逗號轉義符

#endregion

#region 字串轉義
/// <summary>
/// 字串轉義,將雙引號內的:和,分別轉成_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>
/// 字串轉義,將_SEMICOLON和_COMMA分別轉成:和,
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static string StrDecode(string text)
{
return text.Replace(_SEMICOLON, ":").Replace(_COMMA, ",");
}

#endregion

#region JSON最小單元解析

/// <summary>
/// 最小對象轉為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>
/// 最小數組轉為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);//轉義;和,

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數組類
/// </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>
/// 字串轉義,將"{"、"}"、"""
/// </summary>
public class JsonEncode
{
public static readonly string _LEFTBRACES = "@leftbraces";//"{"轉義符
public static readonly string _RIGHTBRACES = "@rightbraces";//"}"轉義符
public static readonly string _LEFTBRACKETS = "@leftbrackets";//"["轉義符
public static readonly string _RIGHTBRACKETS = "@rightbrackets";//"]"轉義符
public static readonly string _DOUBLEQUOTATIONMARKS = "@doubleQuotationMarks";//"""轉義符

#region 字串轉義
/// <summary>
/// 字串轉義,將"{"、"}"、""",分別轉換_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>
/// 字串轉義,將_LEFTBRACES、_RIGHTBRACES、_DOUBLEQUOTATIONMARKS,分別轉換"{"、"}"、"""
/// </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
}

最後要說的,就是比較馬煩的是,現在要取JSON裡的值要用到下面的方法複製代碼 代碼如下:this.Label2.Text = JsonEncode.StrDecodeForDeserialize(json["domain"].ToString());
this.Label2.Text = JsonEncode.StrDecodeForDeserialize(((JSONArray)json["years"])[4].ToString());

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.