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

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

调用示例

View Code
 1 调用示例 
 2 
 3 
 4 
 5 Code highlighting produced by Actipro CodeHighlighter (freeware)
 6 http://www.CodeHighlighter.com/
 7 
 8 -->//序列化
 9 JSONArray jsonArray = new JSONArray();
10 jsonArray.Add("2006");
11 jsonArray.Add("2007");
12 jsonArray.Add("2008");
13 jsonArray.Add("2009");
14 jsonArray.Add("2010");
15 
16 JSONObject jsonObject = new JSONObject();
17 jsonObject.Add("domain", "mzwu.com");
18 jsonObject.Add("years", jsonArray);
19 
20 Console.WriteLine(JSONConvert.SerializeObject(jsonObject));
21 
22 //反序列化
23 JSONObject json = JSONConvert.DeserializeObject("{\"domain\":\"mzwu.com\",\"years\":[2006,2007,2008,2009,2010]}");
24 if (json != null)
25 {
26     Console.WriteLine(json["domain"]);
27     Console.WriteLine(((JSONArray)json["years"])[3]);
28 }

 

posted on 2012-07-25 17:49  捣乃忒  阅读(492)  评论(0编辑  收藏  举报