C#解析Json的类

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Web;  
  4. using System.Text.RegularExpressions;  
  5. using System.Text;  
  6.   
  7. namespace System.JSON  
  8. {  
  9.   
  10.     static class JSONConvert  
  11.     {  
  12.         #region 全局变量  
  13.   
  14.         private static JSONObject _json = new JSONObject();//寄存器   
  15.         private static readonly string _SEMICOLON = "@semicolon";//分号转义符   
  16.         private static readonly string _COMMA = "@comma"//逗号转义符   
  17.  
  18.         #endregion  
  19.  
  20.         #region 字符串转义  
  21.         /// <summary>   
  22.         /// 字符串转义,将双引号内的:和,分别转成_SEMICOLON和_COMMA   
  23.         /// </summary>   
  24.         /// <param name="text"></param>   
  25.         /// <returns></returns>   
  26.         private static string StrEncode(string text)  
  27.         {  
  28.             MatchCollection matches = Regex.Matches(text, "///"[^///"]+///"");  
  29.             foreach (Match match in matches)  
  30.             {  
  31.                 text = text.Replace(match.Value, match.Value.Replace(":", _SEMICOLON).Replace(",", _COMMA));  
  32.             }  
  33.   
  34.             return text;  
  35.         }  
  36.   
  37.         /// <summary>   
  38.         /// 字符串转义,将_SEMICOLON和_COMMA分别转成:和,   
  39.         /// </summary>   
  40.         /// <param name="text"></param>   
  41.         /// <returns></returns>   
  42.         private static string StrDecode(string text)  
  43.         {  
  44.             return text.Replace(_SEMICOLON, ":").Replace(_COMMA, ",");  
  45.         }  
  46.  
  47.         #endregion  
  48.  
  49.         #region JSON最小单元解析  
  50.   
  51.         /// <summary>   
  52.         /// 最小对象转为JSONObject   
  53.         /// </summary>   
  54.         /// <param name="text"></param>   
  55.         /// <returns></returns>   
  56.         private static JSONObject DeserializeSingletonObject(string text)  
  57.         {  
  58.             JSONObject jsonObject = new JSONObject();  
  59.   
  60.             MatchCollection matches = Regex.Matches(text, "(///"(?<key>[^///"]+)///":///"(?<value>[^,///"]+)///")|(///"(?<key>[^///"]+)///":(?<value>[^,///"//}]+))");  
  61.             foreach (Match match in matches)  
  62.             {  
  63.                 string value = match.Groups["value"].Value;  
  64.                 jsonObject.Add(match.Groups["key"].Value, _json.ContainsKey(value) ? _json[value] : StrDecode(value));  
  65.             }  
  66.   
  67.             return jsonObject;  
  68.         }  
  69.   
  70.         /// <summary>   
  71.         /// 最小数组转为JSONArray   
  72.         /// </summary>   
  73.         /// <param name="text"></param>   
  74.         /// <returns></returns>   
  75.         private static JSONArray DeserializeSingletonArray(string text)  
  76.         {  
  77.             JSONArray jsonArray = new JSONArray();  
  78.   
  79.             MatchCollection matches = Regex.Matches(text, "(///"(?<value>[^,///"]+)/")|(?<value>[^,//[//]]+)");  
  80.             foreach (Match match in matches)  
  81.             {  
  82.                 string value = match.Groups["value"].Value;  
  83.                 jsonArray.Add(_json.ContainsKey(value) ? _json[value] : StrDecode(value));  
  84.             }  
  85.   
  86.             return jsonArray;  
  87.         }  
  88.   
  89.         /// <summary>   
  90.         /// 反序列化   
  91.         /// </summary>   
  92.         /// <param name="text"></param>   
  93.         /// <returns></returns>   
  94.         private static string Deserialize(string text)  
  95.         {  
  96.             text = StrEncode(text);//转义;和,   
  97.   
  98.             int count = 0;  
  99.             string key = string.Empty;  
  100.             string pattern = "(//{[^//[//]//{//}]+//})|(//[[^//[//]//{//}]+//])";  
  101.   
  102.             while (Regex.IsMatch(text, pattern))  
  103.             {  
  104.                 MatchCollection matches = Regex.Matches(text, pattern);  
  105.                 foreach (Match match in matches)  
  106.                 {  
  107.                     key = "___key" + count + "___";  
  108.   
  109.                     if (match.Value.Substring(0, 1) == "{")  
  110.                         _json.Add(key, DeserializeSingletonObject(match.Value));  
  111.                     else  
  112.                         _json.Add(key, DeserializeSingletonArray(match.Value));  
  113.   
  114.                     text = text.Replace(match.Value, key);  
  115.   
  116.                     count++;  
  117.                 }  
  118.             }  
  119.             return text;  
  120.         }  
  121.  
  122.         #endregion  
  123.  
  124.         #region 公共接口  
  125.   
  126.         /// <summary>   
  127.         /// 序列化JSONObject对象   
  128.         /// </summary>   
  129.         /// <param name="text"></param>   
  130.         /// <returns></returns>   
  131.         public static JSONObject DeserializeObject(string text)  
  132.         {  
  133.             _json = new JSONObject();  
  134.             return _json[Deserialize(text)] as JSONObject;  
  135.         }  
  136.   
  137.         /// <summary>   
  138.         /// 序列化JSONArray对象   
  139.         /// </summary>   
  140.         /// <param name="text"></param>   
  141.         /// <returns></returns>   
  142.         public static JSONArray DeserializeArray(string text)  
  143.         {  
  144.             _json = new JSONObject();  
  145.             return _json[Deserialize(text)] as JSONArray;  
  146.         }  
  147.   
  148.         /// <summary>   
  149.         /// 反序列化JSONObject对象   
  150.         /// </summary>   
  151.         /// <param name="jsonObject"></param>   
  152.         /// <returns></returns>   
  153.         public static string SerializeObject(JSONObject jsonObject)  
  154.         {  
  155.             StringBuilder sb = new StringBuilder();  
  156.             sb.Append("{");  
  157.             foreach (KeyValuePair<stringobject> kvp in jsonObject)  
  158.             {  
  159.                 if (kvp.Value is JSONObject)  
  160.                 {  
  161.                     sb.Append(string.Format("/"{0}/":{1},", kvp.Key, SerializeObject((JSONObject)kvp.Value)));  
  162.                 }  
  163.                 else if (kvp.Value is JSONArray)  
  164.                 {  
  165.                     sb.Append(string.Format("/"{0}/":{1},", kvp.Key, SerializeArray((JSONArray)kvp.Value)));  
  166.                 }  
  167.                 else if (kvp.Value is String)  
  168.                 {  
  169.                     sb.Append(string.Format("/"{0}/":/"{1}/",", kvp.Key, kvp.Value));  
  170.                 }  
  171.                 else  
  172.                 {  
  173.                     sb.Append(string.Format("/"{0}/":/"{1}/",", kvp.Key, ""));  
  174.                 }  
  175.             }  
  176.             if (sb.Length > 1)  
  177.                 sb.Remove(sb.Length - 1, 1);  
  178.             sb.Append("}");  
  179.             return sb.ToString();  
  180.         }  
  181.   
  182.         /// <summary>   
  183.         /// 反序列化JSONArray对象   
  184.         /// </summary>   
  185.         /// <param name="jsonArray"></param>   
  186.         /// <returns></returns>   
  187.         public static string SerializeArray(JSONArray jsonArray)  
  188.         {  
  189.             StringBuilder sb = new StringBuilder();  
  190.             sb.Append("[");  
  191.             for (int i = 0; i < jsonArray.Count; i++)  
  192.             {  
  193.                 if (jsonArray[i] is JSONObject)  
  194.                 {  
  195.                     sb.Append(string.Format("{0},", SerializeObject((JSONObject)jsonArray[i])));  
  196.                 }  
  197.                 else if (jsonArray[i] is JSONArray)  
  198.                 {  
  199.                     sb.Append(string.Format("{0},", SerializeArray((JSONArray)jsonArray[i])));  
  200.                 }  
  201.                 else if (jsonArray[i] is String)  
  202.                 {  
  203.                     sb.Append(string.Format("/"{0}/",", jsonArray[i]));  
  204.                 }  
  205.                 else  
  206.                 {  
  207.                     sb.Append(string.Format("/"{0}/","""));  
  208.                 }  
  209.   
  210.             }  
  211.             if (sb.Length > 1)  
  212.                 sb.Remove(sb.Length - 1, 1);  
  213.             sb.Append("]");  
  214.             return sb.ToString();  
  215.         }  
  216.         #endregion  
  217.     }  
  218.   
  219.     /// <summary>   
  220.     /// 取出JSON对象类   
  221.     /// </summary>   
  222.     public class JSONObject : Dictionary<stringobject>  
  223.     {  
  224.         public new void Add(string key, object value)  
  225.         {  
  226.             System.Type t = value.GetType();  
  227.   
  228.             if (t.Name == "String")  
  229.             {  
  230.                 value = JSONEncode.StrEncodeForDeserialize(value.ToString());  
  231.             }  
  232.   
  233.             base.Add(key, value);  
  234.         }  
  235.         public override string ToString()  
  236.         {  
  237.             return JSONConvert.SerializeObject(this);  
  238.         }  
  239.         public static JSONObject FromObject(string json)  
  240.         {  
  241.             return JSONConvert.DeserializeObject(json);  
  242.         }  
  243.     }  
  244.   
  245.     /// <summary>   
  246.     /// 取出JSON数组类   
  247.     /// </summary>   
  248.     public class JSONArray : List<object>  
  249.     {  
  250.         public new void Add(object item)  
  251.         {  
  252.             System.Type t = item.GetType();  
  253.   
  254.             if (t.Name == "String")  
  255.             {  
  256.                 item = JSONEncode.StrEncodeForDeserialize(item.ToString());  
  257.             }  
  258.   
  259.             base.Add(item);  
  260.         }  
  261.         public override string ToString()  
  262.         {  
  263.             return JSONConvert.SerializeArray(this);  
  264.         }  
  265.         public JSONArray FromObject(string json)  
  266.         {  
  267.             return JSONConvert.DeserializeArray(json);  
  268.         }  
  269.     }  
  270.   
  271.     /// <summary>   
  272.     /// 字符串转义,将"{"、"}"、"""   
  273.     /// </summary>   
  274.     public class JSONEncode  
  275.     {  
  276.         public static readonly string _LEFTBRACES = "@leftbraces";//"{"转义符   
  277.         public static readonly string _RIGHTBRACES = "@rightbraces";//"}"转义符   
  278.         public static readonly string _LEFTBRACKETS = "@leftbrackets";//"["转义符   
  279.         public static readonly string _RIGHTBRACKETS = "@rightbrackets";//"]"转义符   
  280.         public static readonly string _DOUBLEQUOTATIONMARKS = "@doubleQuotationMarks";//"""转义符   
  281.  
  282.  
  283.         #region 字符串转义  
  284.         /// <summary>   
  285.         /// 字符串转义,将"{"、"}"、""",分别转换_LEFTBRACES、_RIGHTBRACES、_DOUBLEQUOTATIONMARKS   
  286.         /// </summary>   
  287.         /// <param name="text"></param>   
  288.         /// <returns></returns>   
  289.         public static string StrEncodeForDeserialize(string text)  
  290.         {  
  291.             return text  
  292.             .Replace("{", _LEFTBRACES)  
  293.             .Replace("}", _RIGHTBRACES)  
  294.             .Replace("[", _LEFTBRACKETS)  
  295.             .Replace("]", _RIGHTBRACKETS)  
  296.             .Replace("/"", _DOUBLEQUOTATIONMARKS);  
  297.         }  
  298.   
  299.         /// <summary>   
  300.         /// 字符串转义,将_LEFTBRACES、_RIGHTBRACES、_DOUBLEQUOTATIONMARKS,分别转换"{"、"}"、"""   
  301.         /// </summary>   
  302.         /// <param name="text"></param>   
  303.         /// <returns></returns>   
  304.         public static string StrDecodeForDeserialize(string text)  
  305.         {  
  306.             return text.Replace(_LEFTBRACES, "{")  
  307.             .Replace(_RIGHTBRACES, "}")  
  308.             .Replace(_LEFTBRACKETS, "[")  
  309.             .Replace(_RIGHTBRACKETS, "]")  
  310.             .Replace(_DOUBLEQUOTATIONMARKS, "/"");  
  311.         }  
  312.         #endregion  
  313.     }  
  314. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值