现在的位置: 首页 > 综合 > 正文

c# JSON互相访问类。。。。

2013年10月25日 ⁄ 综合 ⁄ 共 7657字 ⁄ 字号 评论关闭

json开始流行了,性能比xml快,所以好多js类库(如jquery)都支持json格式了,通过ASP.NET与js的结合操作json数据传递应该很爽,所以本文使用C#开发一个json类,在看文章前推荐你一些文章:

实用C#中任意类型数据转成JSON格式数据输出
http://www.aspxcs.net/HTML/1000041074.html
以实例讲解json格式应用的json详细教程
http://www.aspxcs.net/HTML/1004241075.html

好了,说看看这个json类的事情,使用本文中的JSONConvert类可将任意JSON字符串转化为JSONObject或JSONArray对象,并获取需要的值,克服了.NET自带JSON类反序列化时需知道并引用序列化时使用的类的缺点。当然,也可以使用JSONConvert类进行序列化,构造出JSON字符串。

下面是类的源码,可以复制直接使用哦。
 

  1. //using System.Collections.Generic;  
  2. //using System.Text;  
  3. //using System.Text.RegularExpressions;  
  4.  
  5. /// <summary>  
  6. /// 类  名:JSONConvert  
  7. /// 描  述:JSON解析类  
  8. /// 编  写:dnawo  
  9. /// 站  点:http://www.mzwu.com/  
  10. /// 日  期:2010-01-06  
  11. /// 版  本:1.1.0  
  12. /// </summary>  
  13. public static class JSONConvert  
  14. {
  15.     #region 全局变量  
  16.  
  17.     private static JSONObject _json = new JSONObject();//寄存器  
  18.     private static readonly string _SEMICOLON = "@semicolon";//分号转义符  
  19.     private static readonly string _COMMA = "@comma"//逗号转义符
  20.  
  21.     #endregion
  22.  
  23.     #region 字符串转义  
  24.     /// <summary>  
  25.     /// 字符串转义,将双引号内的:和,分别转成_SEMICOLON和_COMMA  
  26.     /// </summary>  
  27.     /// <param name="text"></param>  
  28.     /// <returns></returns>  
  29.     private static string StrEncode(string text)  
  30.     {  
  31.         MatchCollection matches = Regex.Matches(text, "///"[^///"] ///"");  
  32.         foreach (Match match in matches)  
  33.         {  
  34.             text = text.Replace(match.Value, match.Value.Replace(":", _SEMICOLON).Replace(",", _COMMA));  
  35.         }  
  36.  
  37.         return text;  
  38.     }  
  39.  
  40.     /// <summary>  
  41.     /// 字符串转义,将_SEMICOLON和_COMMA分别转成:和,  
  42.     /// </summary>  
  43.     /// <param name="text"></param>  
  44.     /// <returns></returns>  
  45.     private static string StrDecode(string text)  
  46.     {  
  47.         return text.Replace(_SEMICOLON, ":").Replace(_COMMA, ",");  
  48.     }
  49.  
  50.     #endregion
  51.  
  52.     #region JSON最小单元解析  
  53.  
  54.     /// <summary>  
  55.     /// 最小对象转为JSONObject  
  56.     /// </summary>  
  57.     /// <param name="text"></param>  
  58.     /// <returns></returns>  
  59.     private static JSONObject DeserializeSingletonObject(string text)  
  60.     {  
  61.         JSONObject jsonObject = new JSONObject();  
  62.  
  63.         MatchCollection matches = Regex.Matches(text, "(///"(?<key>[^///"] )///":///"(?<value>[^,///"] )///")|(///"(?<key>[^///"] )///":(?<value>[^,///"//}] ))");  
  64.         foreach (Match match in matches)  
  65.         {  
  66.             string value = match.Groups["value"].Value;  
  67.             jsonObject.Add(match.Groups["key"].Value, _json.ContainsKey(value) ? _json[value] : StrDecode(value));  
  68.         }  
  69.  
  70.         return jsonObject;  
  71.     }  
  72.  
  73.     /// <summary>  
  74.     /// 最小数组转为JSONArray  
  75.     /// </summary>  
  76.     /// <param name="text"></param>  
  77.     /// <returns></returns>  
  78.     private static JSONArray DeserializeSingletonArray(string text)  
  79.     {  
  80.         JSONArray jsonArray = new JSONArray();  
  81.  
  82.         MatchCollection matches = Regex.Matches(text, "(///"(?<value>[^,///"] )/")|(?<value>[^,//[//]] )");  
  83.         foreach (Match match in matches)  
  84.         {  
  85.             string value = match.Groups["value"].Value;  
  86.             jsonArray.Add(_json.ContainsKey(value) ? _json[value] : StrDecode(value));  
  87.         }  
  88.  
  89.         return jsonArray;  
  90.     }  
  91.  
  92.     /// <summary>  
  93.     /// 反序列化  
  94.     /// </summary>  
  95.     /// <param name="text"></param>  
  96.     /// <returns></returns>  
  97.     private static string Deserialize(string text)  
  98.     {  
  99.         text = StrEncode(text);//转义;和,  
  100.  
  101.         int count = 0;  
  102.         string key = string.Empty;  
  103.         string pattern = "(//{[^//[//]//{//}] //})|(//[[^//[//]//{//}] //])";  
  104.  
  105.         while (Regex.IsMatch(text, pattern))  
  106.         {  
  107.             MatchCollection matches = Regex.Matches(text, pattern);  
  108.             foreach (Match match in matches)  
  109.             {  
  110.                 key = "___key"   count   "___";  
  111.  
  112.                 if (match.Value.Substring(0, 1) == "{")  
  113.                     _json.Add(key, DeserializeSingletonObject(match.Value));  
  114.                 else 
  115.                     _json.Add(key, DeserializeSingletonArray(match.Value));  
  116.  
  117.                 text = text.Replace(match.Value, key);  
  118.  
  119.                 count  ;  
  120.             }  
  121.         }  
  122.         return text;  
  123.     }
  124.  
  125.     #endregion
  126.  
  127.     #region 公共接口  
  128.  
  129.     /// <summary>  
  130.     /// 序列化JSONObject对象  
  131.     /// </summary>  
  132.     /// <param name="text"></param>  
  133.     /// <returns></returns>  
  134.     public static JSONObject DeserializeObject(string text)  
  135.     {  
  136.         return _json[Deserialize(text)] as JSONObject;  
  137.     }  
  138.  
  139.     /// <summary>  
  140.     /// 序列化JSONArray对象  
  141.     /// </summary>  
  142.     /// <param name="text"></param>  
  143.     /// <returns></returns>  
  144.     public static JSONArray DeserializeArray(string text)  
  145.     {  
  146.         return _json[Deserialize(text)] as JSONArray;  
  147.     }  
  148.       
  149.     /// <summary>  
  150.     /// 反序列化JSONObject对象  
  151.     /// </summary>  
  152.     /// <param name="jsonObject"></param>  
  153.     /// <returns></returns>  
  154.     public static string SerializeObject(JSONObject jsonObject)  
  155.     {  
  156.         StringBuilder sb = new StringBuilder();  
  157.         sb.Append("{");  
  158.         foreach (KeyValuePair<stringobject> kvp in jsonObject)  
  159.         {  
  160.             if (kvp.Value is JSONObject)  
  161.             {  
  162.                 sb.Append(string.Format("/"{0}/":{1},", kvp.Key, SerializeObject((JSONObject)kvp.Value)));  
  163.             }  
  164.             else if (kvp.Value is JSONArray)  
  165.             {  
  166.                 sb.Append(string.Format("/"{0}/":{1},", kvp.Key, SerializeArray((JSONArray)kvp.Value)));  
  167.             }  
  168.             else if (kvp.Value is String)  
  169.             {  
  170.                 sb.Append(string.Format("/"{0}/":/"{1}/",", kvp.Key, kvp.Value));  
  171.             }  
  172.             else 
  173.             {  
  174.                 sb.Append(string.Format("/"{0}/":/"{1}/",", kvp.Key, ""));  
  175.             }  
  176.         }  
  177.         if (sb.Length > 1)  
  178.             sb.Remove(sb.Length - 1, 1);  
  179.         sb.Append("}");  
  180.         return sb.ToString();  
  181.     }  
  182.       
  183.     /// <summary>  
  184.     /// 反序列化JSONArray对象  
  185.     /// </summary>  
  186.     /// <param name="jsonArray"></param>  
  187.     /// <returns></returns>  
  188.     public static string SerializeArray(JSONArray jsonArray)  
  189.     {  
  190.         StringBuilder sb = new StringBuilder();  
  191.         sb.Append("[");  
  192.         for (int i = 0; i < jsonArray.Count; i  )  
  193.         {  
  194.             if (jsonArray[i] is JSONObject)  
  195.             {  
  196.                 sb.Append(string.Format("{0},", SerializeObject((JSONObject)jsonArray[i])));  
  197.             }  
  198.             else if (jsonArray[i] is JSONArray)  
  199.             {  
  200.                 sb.Append(string.Format("{0},", SerializeArray((JSONArray)jsonArray[i])));  
  201.             }  
  202.             else if (jsonArray[i] is String)  
  203.             {  
  204.                 sb.Append(string.Format("/"{0}/",", jsonArray[i]));  
  205.             }  
  206.             else 
  207.             {  
  208.                 sb.Append(string.Format("/"{0}/","""));  
  209.             }  
  210.  
  211.         }  
  212.         if (sb.Length > 1)  
  213.             sb.Remove(sb.Length - 1, 1);  
  214.         sb.Append("]");  
  215.         return sb.ToString();  
  216.     }
  217.     #endregion  
  218. }  
  219.  
  220. /// <summary>  
  221. /// 类  名:JSONObject  
  222. /// 描  述:JSON对象类  
  223. /// 版  本:1.1.0  
  224. /// 更新历史:  
  225. ///     2010-01-06  继承Dictionary<TKey, TValue>代替this[]  
  226. /// </summary>  
  227. public class JSONObject : Dictionary<stringobject>  
  228. {}  
  229.  
  230. /// <summary>  
  231. /// 类  名:JSONArray  
  232. /// 描  述:JSON数组类  
  233. /// 版  本:1.1.0  
  234. /// 更新历史:  
  235. ///     2010-01-06  继承List<T>代替this[]  
  236. /// </summary>  
  237. public class JSONArray : List<object>  
  238. {} 

嗯,json写完了,下面来看下使用的方法:
 

  1. //序列化  
  2. JSONArray jsonArray = new JSONArray();  
  3. jsonArray.Add("2006");  
  4. jsonArray.Add("2007");  
  5. jsonArray.Add("2008");  
  6. jsonArray.Add("2009");  
  7. jsonArray.Add("2010");  
  8.  
  9. JSONObject jsonObject = new JSONObject();  
  10. jsonObject.Add("domain""mzwu.com");  
  11. jsonObject.Add("years", jsonArray);  
  12.  
  13. Console.WriteLine(JSONConvert.SerializeObject(jsonObject));  
  14.  
  15. //反序列化  "{/"domain/":/"mzwu.com/",/"years/":[2006,2007,2008,2009,2010]}"  
  16. JSONObject json = JSONConvert.DeserializeObject(JSONConvert.SerializeObject(jsonObject));  
  17. if (json != null)  
  18. {  
  19.     Console.WriteLine(json["domain"]);  
  20.     Console.WriteLine(((JSONArray)json["years"])[3]);  
  21. }  

 

抱歉!评论已关闭.