欢迎光临

木子屋

标题: JSON解析类(C#)

作者: dnawo

日期: 2010-01-06 04:15 PM

分类: Web编程

内容: 复制内容到剪贴板 程序代码//using System.Collections.Generic;
//using System.Text;
//using System.Text.RegularExpressions;
/// <summary>
/// 类 名：JSONConvert
/// 描 述：JSON解析类
/// 编 写：dnawo
/// 站 点：http://www.mzwu.com/
/// 日 期：2010-01-06
/// 版 本：1.0.0
/// </summary>
public 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[match.Groups["key"].Value] = _json[value] == null ? StrDecode(value) : _json[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[jsonArray.Count] = _json[value] == null ? StrDecode(value) : _json[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[key] = DeserializeSingletonObject(match.Value);
else
_json[key] = DeserializeSingletonArray(match.Value);
text = text.Replace(match.Value, key);
count++;
}
}
return text;
}
#endregion
#region 公共接口
/// <summary>
/// 将JSON字符串转为JSONObject对象
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static JSONObject DeserializeObject(string text)
{
return _json[Deserialize(text)] as JSONObject;
}
/// <summary>
/// 将JSON字符串转为JSONArray数组
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static JSONArray DeserializeArray(string text)
{
return _json[Deserialize(text)] as JSONArray;
}
#endregion
}
/// <summary>
/// 类 名：JSONObject
/// 描 述：JSON对象类
/// 编 写：dnawo
/// 站 点：http://www.mzwu.com/
/// 日 期：2010-01-06
/// 版 本：1.0.0
/// </summary>
public class JSONObject
{
Dictionary<string, object> _dict = new Dictionary<string, object>();
/// <summary>
/// 关联数组
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public object this[string key]
{
get
{
if (_dict.ContainsKey(key))
return _dict[key];
else
return null;
}
set
{
if (!string.IsNullOrEmpty(key))
{
if (_dict.ContainsKey(key))
if (value == null)
_dict.Remove(key);
else
_dict[key] = value;
else
_dict.Add(key, value);
}
}
}
/// <summary>
/// 重写,序列化对象
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
foreach (KeyValuePair<string, object> kvp in _dict)
{
if (kvp.Value is JSONObject)
{
sb.Append(string.Format("\"{0}\":{1},", kvp.Key, ((JSONObject)kvp.Value).ToString()));
}
else if (kvp.Value is JSONArray)
{
sb.Append(string.Format("\"{0}\":{1},", kvp.Key, ((JSONArray)kvp.Value).ToString()));
}
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
/// 描 述：JSON数组类
/// 编 写：dnawo
/// 站 点：http://www.mzwu.com/
/// 日 期：2010-01-06
/// 版 本：1.0.0
/// </summary>
public class JSONArray
{
List<object> _list = new List<object>();
/// <summary>
/// 索引器
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public object this[int index]
{
get
{
if (index < _list.Count)
return _list[index];
else
return null;
}
set
{
if (index < _list.Count)
_list[index] = value;
else
_list.Add(value);
}
}
/// <summary>
/// 包含的元素总数
/// </summary>
public int Count
{
get
{
return _list.Count;
}
}
/// <summary>
/// 重写,序列化对象
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
for (int i = 0; i < _list.Count; i++)
{
if (_list[i] is JSONObject)
{
sb.Append(string.Format("{0},", ((JSONObject)_list[i]).ToString()));
}
else if (_list[i] is JSONArray)
{
sb.Append(string.Format("{0},", ((JSONArray)_list[i]).ToString()));
}
else if (_list[i] is String)
{
sb.Append(string.Format("\"{0}\",", _list[i]));
}
else
{
sb.Append(string.Format("\"{0}\",", ""));
}
}
if (sb.Length > 1)
sb.Remove(sb.Length - 1, 1);
sb.Append("]");
return sb.ToString();
}
}
调用示例：
复制内容到剪贴板 程序代码//序列化
JSONArray jsonArray = new JSONArray();
jsonArray[jsonArray.Count] = "2006";
jsonArray[jsonArray.Count] = "2007";
jsonArray[jsonArray.Count] = "2008";
jsonArray[jsonArray.Count] = "2009";
jsonArray[jsonArray.Count] = "2010";
JSONObject jsonObject = new JSONObject();
jsonObject["domain"] = "mzwu.com";
jsonObject["years"] = jsonArray;
Console.WriteLine(jsonObject.ToString());
//反序列化 "{\"domain\":\"mzwu.com\",\"years\":[2006,2007,2008,2009,2010]}"
JSONObject json = JSONConvert.DeserializeObject(jsonObject.ToString());
if (json != null)
{
Console.WriteLine(json["domain"]);
Console.WriteLine(((JSONArray)json["years"])[3]);
Console.WriteLine(json.ToString());
}

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.332 ms

返回

标题: JSON解析类(C#)

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.332 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.361 ms

返回