天使半只翼

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

 

调试代码
 1 调试代码
 2  JSONArray jsonArray = new JSONArray();
 3             jsonArray.Add("2006");
 4             jsonArray.Add("2007");
 5             jsonArray.Add("2008");
 6 
 7             JSONArray jsonArray1 = new JSONArray();
 8             jsonArray1.Add("2006");
 9             jsonArray1.Add("2007");
10             jsonArray1.Add("2008");
11 
12             JSONObject jsonObject = new JSONObject();
13             jsonObject.Add("domain", "mzwu.com");
14             jsonObject.Add("years", jsonArray);
15             jsonObject["domain"] = jsonArray1;
16 
17             Console.WriteLine(JSONConvert.SerializeObject(jsonObject));
18 
19             JSONObject json = JSONConvert.DeserializeObject(JSONConvert.SerializeObject(jsonObject));
20             if (json != null)
21             {
22                 Console.WriteLine(json["domain"]);
23                 Console.WriteLine(((JSONArray)json["years"])[2]);
24             }
posted on 2012-08-06 17:23  天使半只翼  阅读(1573)  评论(0编辑  收藏  举报