using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace JsonHelper
{
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 字符串转义
///
/// 字符串转义,将双引号内的:和,分别转成_SEMICOLON和_COMMA
///
///
///
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;
}
///
/// 字符串转义,将_SEMICOLON和_COMMA分别转成:和,
///
///
///
private static string StrDecode(string text)
{
return text.Replace(_SEMICOLON, ":").Replace(_COMMA, ",");
}
#endregion
#region JSON最小单元解析
///
/// 最小对象转为JSONObject
///
///
///
private static JSONObject DeserializeSingletonObject(string text)
{
JSONObject jsonObject = new JSONObject();
MatchCollection matches = Regex.Matches(text, "(\\\"(?[^\\\"] )\\\":\\\"(?[^,\\\"] )\\\")|(\\\"(?[^\\\"] )\\\":(?[^,\\\"\\}] ))");
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;
}
///
/// 最小数组转为JSONArray
///
///
///
private static JSONArray DeserializeSingletonArray(string text)
{
JSONArray jsonArray = new JSONArray();
MatchCollection matches = Regex.Matches(text, "(\\\"(?[^,\\\"] )\")|(?[^,\\[\\]] )");
foreach (Match match in matches)
{
string value = match.Groups["value"].Value;
jsonArray.Add(_json.ContainsKey(value) ? _json[value] : StrDecode(value));
}
return jsonArray;
}
///
/// 反序列化
///
///
///
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 公共接口
///
/// 序列化JSONObject对象
///
///
///
public static JSONObject DeserializeObject(string text)
{
return _json[Deserialize(text)] as JSONObject;
}
///
/// 序列化JSONArray对象
///
///
///
public static JSONArray DeserializeArray(string text)
{
return _json[Deserialize(text)] as JSONArray;
}
///
/// 反序列化JSONObject对象
///
///
///
public static string SerializeObject(JSONObject jsonObject)
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
foreach (KeyValuePair 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();
}
///
/// 反序列化JSONArray对象
///
///
///
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
}
///
/// 类 名:JSONObject
/// 描 述:JSON对象类
/// 版 本:1.1.0
/// 更新历史:
/// 2010-01-06 继承Dictionary代替this[]
///
public class JSONObject : Dictionary
{ }
///
/// 类 名:JSONArray
/// 描 述:JSON数组类
/// 版 本:1.1.0
/// 更新历史:
/// 2010-01-06 继承List代替this[]
///
public class JSONArray : List