JSON序列化必看以及序列化工具类
1、要序列化的类必须用 [DataContract] 特性标识
2、需要序列化的属性应用 [DataMember] 特性标识,没有该特性则表示不序列化该属性。类亦如此!
3、可以网络上找封装好的序列化类工具,也可以引用 System.json 程序集
1 // /*--------------- 2 // // 使用地方:eKing 警备系统 【终端和服务器之间的数据同步】 3 // // 4 // // 文件名:JsonUtils.cs 5 // // 文件功能描述: 6 // // 指定对象序列化成JSON 7 // // 将JSON反序列化成原对象 8 // // JsonUtils.Serialize(result); --- Serialize() 方法支持序列化(对象嵌套对象)的需求 9 // // 可直接调用Serialize()方法,可同时序列化指定对象包含的自定义对象,甚至List集合 10 // // 11 // // 创建标识:米立林20140319 12 // // 13 // // 修改标识: 14 // // 修改描述: 15 // //----------------------------------------------------------------*/ 16 using System.Collections.Generic; 17 using System.Collections.ObjectModel; 18 using System.IO; 19 using System.Linq; 20 using System.Reflection; 21 using System.Runtime.Serialization.Json; 22 using System.Text; 23 using System.Web.Script.Serialization; 24 namespace BJJDKJ.PEDIMS.SyncService 25 { 26 public class JsonUtils 27 { 28 // Methods 29 public static T Deserialize<T>(string json) 30 { 31 //将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式 32 string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; 33 MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate); 34 Regex reg = new Regex(p); 35 json = reg.Replace(json, matchEvaluator); 36 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); 37 using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json))) 38 { 39 return (T)serializer.ReadObject(stream); 40 } 41 } 42 public static Dictionary<string, object> DeserializeDictionaryToJson(string json) 43 { 44 Dictionary<string, object> dictionary2; 45 JavaScriptSerializer serializer = new JavaScriptSerializer(); 46 serializer.RegisterConverters(new Collection<JavaScriptConverter>()); 47 dictionary2 = serializer.Deserialize<Dictionary<string, object>>(json); 48 return dictionary2; 49 } 50 public static T DeserializeEntityByBase64<T>(string json) 51 { 52 List<T> list = DeserializeListByBase64<T>(json); 53 if ((list != null) && (list.Count > 0)) 54 { 55 return list[0]; 56 } 57 T local = Deserialize<T>(json); 58 if (local != null) 59 { 60 PropertyInfo[] properties = local.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); 61 foreach (PropertyInfo info in properties) 62 { 63 if (info.PropertyType == typeof(string)) 64 { 65 object obj2 = info.GetValue(local, null); 66 if (obj2 != null) 67 { 68 //info.SetValue(local, ConvertUtils.ConvertFromBase64String(obj2.ToString()), null); 69 info.SetValue(local, obj2.ToString(), null); 70 } 71 } 72 } 73 return local; 74 } 75 return default(T); 76 } 77 public static List<T> DeserializeListByBase64<T>(string json) 78 { 79 List<T> list = Deserialize<List<T>>(json); 80 if ((list != null) && (list.Count > 0)) 81 { 82 foreach (T local in list) 83 { 84 PropertyInfo[] properties = local.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); 85 foreach (PropertyInfo info in properties) 86 { 87 if (info.PropertyType == typeof(string)) 88 { 89 object obj2 = info.GetValue(local, null); 90 if (obj2 != null) 91 { 92 info.SetValue(local, ConvertUtils.ConvertFromBase64String(obj2.ToString()), null); 93 } 94 } 95 } 96 } 97 } 98 return list; 99 } 100 public static string Serialize<T>(T data) 101 { 102 DataContractJsonSerializer serializer = new DataContractJsonSerializer(data.GetType()); 103 using (MemoryStream stream = new MemoryStream()) 104 { 105 serializer.WriteObject(stream, data); 106 string jsonStr = Encoding.UTF8.GetString(stream.ToArray()); 107 //替换Json的Date字符串 108 //string p = @"/\//Date/((/d+)/+/d+/)/\//"; 109 /*////Date/((([/+/-]/d+)|(/d+))[/+/-]/d+/)////*/ 110 string p = @"\\/Date\((\d+)\+\d+\)\\/"; 111 MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString); 112 Regex reg = new Regex(p); 113 jsonStr = reg.Replace(jsonStr, matchEvaluator); 114 return jsonStr; 115 } 116 } 117 public static string SerializeEntityByBase64<T>(T t) 118 { 119 List<T> list = new List<T> { t }; 120 return SerializeListByBase64(list); 121 } 122 public static string SerializeJsonToDictionary(Dictionary<string, object> dic) 123 { 124 string str2; 125 JavaScriptSerializer serializer = new JavaScriptSerializer(); 126 serializer.RegisterConverters(new Collection<JavaScriptConverter>()); 127 str2 = serializer.Serialize(dic); 128 return str2; 129 } 130 public static string SerializeListByBase64<T>(List<T> list) 131 { 132 if ((list != null) && (list.Count > 0)) 133 { 134 foreach (T local in list) 135 { 136 PropertyInfo[] properties = local.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); 137 foreach (PropertyInfo info in properties) 138 { 139 if (info.PropertyType == typeof(string)) 140 { 141 if (info.Name == "SIM_Police") 142 { 143 } 144 object obj2 = info.GetValue(local, null); 145 if (obj2 != null) 146 { 147 info.SetValue(local, ConvertUtils.ConvertToBase64String(obj2.ToString()), null); 148 } 149 } 150 } 151 } 152 return Serialize(list); 153 } 154 return ""; 155 } 156 private static string WipeSpecialChar(string str) 157 { 158 StringBuilder builder = new StringBuilder(); 159 for (int i = 0; i < str.Length; i++) 160 { 161 char ch = str.ElementAt(i); 162 char ch2 = ch; 163 if (ch2 <= \'\\'\') 164 { 165 switch (ch2) 166 { 167 case \'\b\': 168 { 169 builder.Append(@"\b"); 170 continue; 171 } 172 case \'\t\': 173 { 174 builder.Append(@"\t"); 175 continue; 176 } 177 case \'\n\': 178 { 179 builder.Append(@"\n"); 180 continue; 181 } 182 case \'\v\': 183 goto Label_00C7; 184 case \'\f\': 185 { 186 builder.Append(@"\f"); 187 continue; 188 } 189 case \'\r\': 190 { 191 builder.Append(@"\r"); 192 continue; 193 } 194 case \'\\'\': 195 goto Label_00B9; 196 } 197 goto Label_00C7; 198 } 199 if (ch2 != \'/\') 200 { 201 if (ch2 != \'\\\') 202 { 203 goto Label_00C7; 204 } 205 builder.Append(@"\\"); 206 } 207 else 208 { 209 builder.Append(@"\/"); 210 } 211 continue; 212 Label_00B9: 213 builder.Append(@"\\'"); 214 continue; 215 Label_00C7: 216 builder.Append(ch); 217 } 218 return builder.ToString(); 219 } 220 /// <summary> 221 /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串 222 /// </summary> 223 private static string ConvertJsonDateToDateString(Match m) 224 { 225 string result = string.Empty; 226 DateTime dt = new DateTime(1970, 1, 1); 227 dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); 228 dt = dt.ToLocalTime(); 229 result = dt.ToString("yyyy-MM-dd HH:mm:ss"); 230 return result; 231 } 232 /// <summary> 233 /// 将时间字符串转为Json时间 234 /// </summary> 235 private static string ConvertDateStringToJsonDate(Match m) 236 { 237 string result = string.Empty; 238 DateTime dt = DateTime.Parse(m.Groups[0].Value); 239 dt = dt.ToUniversalTime(); 240 TimeSpan ts = dt - DateTime.Parse("1970-01-01"); 241 result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds); 242 return result; 243 } 244 } 245 }
版权声明:本文为minily原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。