首页 > 编程 > .NET > 正文

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

2024-07-10 12:42:25
字体:
来源:转载
供稿:网友
全部代码如下。 
代码如下:
/// <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 = "(//{[^//[//]//{//}]+//})|(//[[^//[//]//{//}]+//])";
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表