• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#json解析类--转载

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

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             //反序列化  "{/"domain/":/"mzwu.com/",/"years/":[2006,2007,2008,2009,2010]}"   
15             JSONObject json = JSONConvert.DeserializeObject(JSONConvert.SerializeObject(jsonObject));
16             if (json != null)
17             {
18                 Console.WriteLine(json["domain"]);
19                 Console.WriteLine(((JSONArray)json["years"])[3]);
20             }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
【机试题】c#是否是素数,找出比它大的第一个素数发布时间:2022-07-18
下一篇:
C#结构体初始化发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap