JsonSerializer.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. //
  2. // JsonSerializer.cs
  3. //
  4. // Author:
  5. // Marek Habersack <[email protected]>
  6. //
  7. // (C) 2008 Novell, Inc. http://novell.com/
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections;
  31. using System.Collections.Generic;
  32. using System.Data;
  33. using System.Globalization;
  34. using System.IO;
  35. using System.Reflection;
  36. using System.Text;
  37. namespace System.Web.Script.Serialization
  38. {
  39. internal sealed class JsonSerializer
  40. {
  41. internal static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
  42. static readonly DateTime MinimumJavaScriptDate = new DateTime (100, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  43. static readonly MethodInfo serializeGenericDictionary = typeof (JsonSerializer).GetMethod ("SerializeGenericDictionary", BindingFlags.NonPublic | BindingFlags.Instance);
  44. Dictionary <object, bool> objectCache;
  45. JavaScriptSerializer serializer;
  46. JavaScriptTypeResolver typeResolver;
  47. int recursionLimit;
  48. int maxJsonLength;
  49. int recursionDepth;
  50. Dictionary <Type, MethodInfo> serializeGenericDictionaryMethods;
  51. public JsonSerializer (JavaScriptSerializer serializer)
  52. {
  53. if (serializer == null)
  54. throw new ArgumentNullException ("serializer");
  55. this.serializer = serializer;
  56. typeResolver = serializer.TypeResolver;
  57. recursionLimit = serializer.RecursionLimit;
  58. maxJsonLength = serializer.MaxJsonLength;
  59. }
  60. public void Serialize (object obj, StringBuilder output)
  61. {
  62. if (output == null)
  63. throw new ArgumentNullException ("output");
  64. DoSerialize (obj, output);
  65. }
  66. public void Serialize (object obj, TextWriter output)
  67. {
  68. if (output == null)
  69. throw new ArgumentNullException ("output");
  70. StringBuilder sb = new StringBuilder ();
  71. DoSerialize (obj, sb);
  72. output.Write (sb.ToString ());
  73. }
  74. void DoSerialize (object obj, StringBuilder output)
  75. {
  76. recursionDepth = 0;
  77. objectCache = new Dictionary <object, bool> ();
  78. SerializeValue (obj, output);
  79. }
  80. void SerializeValue (object obj, StringBuilder output)
  81. {
  82. recursionDepth++;
  83. SerializeValueImpl (obj, output);
  84. recursionDepth--;
  85. }
  86. void SerializeValueImpl (object obj, StringBuilder output)
  87. {
  88. if (recursionDepth > recursionLimit)
  89. throw new ArgumentException ("Recursion limit has been exceeded while serializing object of type '{0}'", obj != null ? obj.GetType ().ToString () : "[null]");
  90. if (obj == null || DBNull.Value.Equals (obj)) {
  91. output.AppendCount (maxJsonLength, "null");
  92. return;
  93. }
  94. Type valueType = obj.GetType ();
  95. JavaScriptConverter jsc = serializer.GetConverter (valueType);
  96. if (jsc != null) {
  97. IDictionary <string, object> result = jsc.Serialize (obj, serializer);
  98. if (result == null) {
  99. output.AppendCount (maxJsonLength, "null");
  100. return;
  101. }
  102. if (typeResolver != null) {
  103. string typeId = typeResolver.ResolveTypeId (valueType);
  104. if (!String.IsNullOrEmpty (typeId))
  105. result [JavaScriptSerializer.SerializedTypeNameKey] = typeId;
  106. }
  107. SerializeValue (result, output);
  108. return;
  109. }
  110. TypeCode typeCode = Type.GetTypeCode (valueType);
  111. switch (typeCode) {
  112. case TypeCode.String:
  113. WriteValue (output, (string)obj);
  114. return;
  115. case TypeCode.Char:
  116. WriteValue (output, (char)obj);
  117. return;
  118. case TypeCode.Boolean:
  119. WriteValue (output, (bool)obj);
  120. return;
  121. case TypeCode.SByte:
  122. case TypeCode.Int16:
  123. case TypeCode.UInt16:
  124. case TypeCode.Int32:
  125. case TypeCode.Byte:
  126. case TypeCode.UInt32:
  127. case TypeCode.Int64:
  128. case TypeCode.UInt64:
  129. if (valueType.IsEnum) {
  130. WriteEnumValue (output, obj, typeCode);
  131. return;
  132. }
  133. goto case TypeCode.Decimal;
  134. case TypeCode.Single:
  135. WriteValue (output, (float)obj);
  136. return;
  137. case TypeCode.Double:
  138. WriteValue (output, (double)obj);
  139. return;
  140. case TypeCode.Decimal:
  141. WriteValue (output, obj as IConvertible);
  142. return;
  143. case TypeCode.DateTime:
  144. WriteValue (output, (DateTime)obj);
  145. return;
  146. }
  147. if (typeof (Uri).IsAssignableFrom (valueType)) {
  148. WriteValue (output, (Uri)obj);
  149. return;
  150. }
  151. if (typeof (Guid).IsAssignableFrom (valueType)) {
  152. WriteValue (output, (Guid)obj);
  153. return;
  154. }
  155. IConvertible convertible = obj as IConvertible;
  156. if (convertible != null) {
  157. WriteValue (output, convertible);
  158. return;
  159. }
  160. try {
  161. if (objectCache.ContainsKey (obj))
  162. throw new InvalidOperationException ("Circular reference detected.");
  163. objectCache.Add (obj, true);
  164. Type closedIDict = GetClosedIDictionaryBase(valueType);
  165. if (closedIDict != null) {
  166. if (serializeGenericDictionaryMethods == null)
  167. serializeGenericDictionaryMethods = new Dictionary <Type, MethodInfo> ();
  168. MethodInfo mi;
  169. if (!serializeGenericDictionaryMethods.TryGetValue (closedIDict, out mi)) {
  170. Type[] types = closedIDict.GetGenericArguments ();
  171. mi = serializeGenericDictionary.MakeGenericMethod (types [0], types [1]);
  172. serializeGenericDictionaryMethods.Add (closedIDict, mi);
  173. }
  174. mi.Invoke (this, new object[] {output, obj});
  175. return;
  176. }
  177. IDictionary dict = obj as IDictionary;
  178. if (dict != null) {
  179. SerializeDictionary (output, dict);
  180. return;
  181. }
  182. IEnumerable enumerable = obj as IEnumerable;
  183. if (enumerable != null) {
  184. SerializeEnumerable (output, enumerable);
  185. return;
  186. }
  187. SerializeArbitraryObject (output, obj, valueType);
  188. } finally {
  189. objectCache.Remove (obj);
  190. }
  191. }
  192. Type GetClosedIDictionaryBase(Type t) {
  193. if(t.IsGenericType && typeof (IDictionary <,>).IsAssignableFrom (t.GetGenericTypeDefinition ()))
  194. return t;
  195. foreach(Type iface in t.GetInterfaces()) {
  196. if(iface.IsGenericType && typeof (IDictionary <,>).IsAssignableFrom (iface.GetGenericTypeDefinition ()))
  197. return iface;
  198. }
  199. return null;
  200. }
  201. bool ShouldIgnoreMember (MemberInfo mi, out MethodInfo getMethod)
  202. {
  203. getMethod = null;
  204. if (mi.IsDefined (typeof (ScriptIgnoreAttribute), true))
  205. return true;
  206. FieldInfo fi = mi as FieldInfo;
  207. if (fi != null)
  208. return false;
  209. PropertyInfo pi = mi as PropertyInfo;
  210. if (pi == null)
  211. return true;
  212. getMethod = pi.GetGetMethod ();
  213. if (getMethod == null || getMethod.GetParameters ().Length > 0) {
  214. getMethod = null;
  215. return true;
  216. }
  217. return false;
  218. }
  219. object GetMemberValue (object obj, MemberInfo mi)
  220. {
  221. FieldInfo fi = mi as FieldInfo;
  222. if (fi != null)
  223. return fi.GetValue (obj);
  224. MethodInfo method = mi as MethodInfo;
  225. if (method == null)
  226. throw new InvalidOperationException ("Member is not a method (internal error).");
  227. object ret;
  228. try {
  229. ret = method.Invoke (obj, null);
  230. } catch (TargetInvocationException niex) {
  231. if (niex.InnerException is NotImplementedException) {
  232. Console.WriteLine ("!!! COMPATIBILITY WARNING. FEATURE NOT IMPLEMENTED. !!!");
  233. Console.WriteLine (niex);
  234. Console.WriteLine ("!!! RETURNING NULL. PLEASE LET MONO DEVELOPERS KNOW ABOUT THIS EXCEPTION. !!!");
  235. return null;
  236. }
  237. throw;
  238. }
  239. return ret;
  240. }
  241. void SerializeArbitraryObject (StringBuilder output, object obj, Type type)
  242. {
  243. output.AppendCount (maxJsonLength, "{");
  244. bool first = true;
  245. if (typeResolver != null) {
  246. string typeId = typeResolver.ResolveTypeId (type);
  247. if (!String.IsNullOrEmpty (typeId)) {
  248. WriteDictionaryEntry (output, first, JavaScriptSerializer.SerializedTypeNameKey, typeId);
  249. first = false;
  250. }
  251. }
  252. MemberInfo[] members = type.GetMembers (BindingFlags.Public | BindingFlags.Instance);
  253. MemberInfo member;
  254. MethodInfo getMethod;
  255. string name;
  256. foreach (MemberInfo mi in members) {
  257. if (ShouldIgnoreMember (mi, out getMethod))
  258. continue;
  259. name = mi.Name;
  260. if (getMethod != null)
  261. member = getMethod;
  262. else
  263. member = mi;
  264. WriteDictionaryEntry (output, first, name, GetMemberValue (obj, member));
  265. if (first)
  266. first = false;
  267. }
  268. output.AppendCount (maxJsonLength, "}");
  269. }
  270. void SerializeEnumerable (StringBuilder output, IEnumerable enumerable)
  271. {
  272. output.AppendCount (maxJsonLength, "[");
  273. bool first = true;
  274. foreach (object value in enumerable) {
  275. if (!first)
  276. output.AppendCount (maxJsonLength, ',');
  277. SerializeValue (value, output);
  278. if (first)
  279. first = false;
  280. }
  281. output.AppendCount (maxJsonLength, "]");
  282. }
  283. void SerializeDictionary (StringBuilder output, IDictionary dict)
  284. {
  285. output.AppendCount (maxJsonLength, "{");
  286. bool first = true;
  287. string key;
  288. foreach (DictionaryEntry entry in dict) {
  289. WriteDictionaryEntry (output, first, entry.Key as string, entry.Value);
  290. if (first)
  291. first = false;
  292. }
  293. output.AppendCount (maxJsonLength, "}");
  294. }
  295. void SerializeGenericDictionary <TKey, TValue> (StringBuilder output, IDictionary <TKey, TValue> dict)
  296. {
  297. output.AppendCount (maxJsonLength, "{");
  298. bool first = true;
  299. string key;
  300. foreach (KeyValuePair <TKey, TValue> kvp in dict) {
  301. WriteDictionaryEntry (output, first, kvp.Key as string, kvp.Value);
  302. if (first)
  303. first = false;
  304. }
  305. output.AppendCount (maxJsonLength, "}");
  306. }
  307. void WriteDictionaryEntry (StringBuilder output, bool skipComma, string key, object value)
  308. {
  309. if (key == null)
  310. throw new InvalidOperationException ("Only dictionaries with keys convertible to string are supported.");
  311. if (!skipComma)
  312. output.AppendCount (maxJsonLength, ',');
  313. WriteValue (output, key);
  314. output.AppendCount (maxJsonLength, ':');
  315. SerializeValue (value, output);
  316. }
  317. void WriteEnumValue (StringBuilder output, object value, TypeCode typeCode)
  318. {
  319. switch (typeCode) {
  320. case TypeCode.SByte:
  321. output.AppendCount (maxJsonLength, (sbyte)value);
  322. return;
  323. case TypeCode.Int16:
  324. output.AppendCount (maxJsonLength, (short)value);
  325. return;
  326. case TypeCode.UInt16:
  327. output.AppendCount (maxJsonLength, (ushort)value);
  328. return;
  329. case TypeCode.Int32:
  330. output.AppendCount (maxJsonLength, (int)value);
  331. return;
  332. case TypeCode.Byte:
  333. output.AppendCount (maxJsonLength, (byte)value);
  334. return;
  335. case TypeCode.UInt32:
  336. output.AppendCount (maxJsonLength, (uint)value);
  337. return;
  338. case TypeCode.Int64:
  339. output.AppendCount (maxJsonLength, (long)value);
  340. return;
  341. case TypeCode.UInt64:
  342. output.AppendCount (maxJsonLength, (ulong)value);
  343. return;
  344. default:
  345. throw new InvalidOperationException (String.Format ("Invalid type code for enum: {0}", typeCode));
  346. }
  347. }
  348. void WriteValue (StringBuilder output, float value)
  349. {
  350. output.AppendCount (maxJsonLength, value.ToString ("r"));
  351. }
  352. void WriteValue (StringBuilder output, double value)
  353. {
  354. output.AppendCount (maxJsonLength, value.ToString ("r"));
  355. }
  356. void WriteValue (StringBuilder output, Guid value)
  357. {
  358. WriteValue (output, value.ToString ());
  359. }
  360. void WriteValue (StringBuilder output, Uri value)
  361. {
  362. WriteValue (output, value.GetComponents (UriComponents.AbsoluteUri, UriFormat.UriEscaped));
  363. }
  364. void WriteValue (StringBuilder output, DateTime value)
  365. {
  366. value = value.ToUniversalTime ();
  367. if (value < MinimumJavaScriptDate)
  368. value = MinimumJavaScriptDate;
  369. long ticks = (value.Ticks - InitialJavaScriptDateTicks) / (long)10000;
  370. output.AppendCount (maxJsonLength, "\"\\/Date(" + ticks + ")\\/\"");
  371. }
  372. void WriteValue (StringBuilder output, IConvertible value)
  373. {
  374. output.AppendCount (maxJsonLength, value.ToString (CultureInfo.InvariantCulture));
  375. }
  376. void WriteValue (StringBuilder output, bool value)
  377. {
  378. output.AppendCount (maxJsonLength, value ? "true" : "false");
  379. }
  380. void WriteValue (StringBuilder output, char value)
  381. {
  382. if (value == '\0') {
  383. output.AppendCount (maxJsonLength, "null");
  384. return;
  385. }
  386. WriteValue (output, value.ToString ());
  387. }
  388. void WriteValue (StringBuilder output, string value)
  389. {
  390. if (String.IsNullOrEmpty (value)) {
  391. output.AppendCount (maxJsonLength, "\"\"");
  392. return;
  393. }
  394. output.AppendCount (maxJsonLength, "\"");
  395. char c;
  396. for (int i = 0; i < value.Length; i++) {
  397. c = value [i];
  398. switch (c) {
  399. case '\t':
  400. output.AppendCount (maxJsonLength, @"\t");
  401. break;
  402. case '\n':
  403. output.AppendCount (maxJsonLength, @"\n");
  404. break;
  405. case '\r':
  406. output.AppendCount (maxJsonLength, @"\r");
  407. break;
  408. case '\f':
  409. output.AppendCount (maxJsonLength, @"\f");
  410. break;
  411. case '\b':
  412. output.AppendCount (maxJsonLength, @"\b");
  413. break;
  414. case '<':
  415. output.AppendCount (maxJsonLength, @"\u003c");
  416. break;
  417. case '>':
  418. output.AppendCount (maxJsonLength, @"\u003e");
  419. break;
  420. case '"':
  421. output.AppendCount (maxJsonLength, "\\\"");
  422. break;
  423. case '\'':
  424. output.AppendCount (maxJsonLength, @"\u0027");
  425. break;
  426. case '\\':
  427. output.AppendCount (maxJsonLength, @"\\");
  428. break;
  429. default:
  430. if (c > '\u001f')
  431. output.AppendCount (maxJsonLength, c);
  432. else {
  433. output.Append("\\u00");
  434. int intVal = (int) c;
  435. output.AppendCount (maxJsonLength, (char) ('0' + (intVal >> 4)));
  436. intVal &= 0xf;
  437. output.AppendCount (maxJsonLength, (char) (intVal < 10 ? '0' + intVal : 'a' + (intVal - 10)));
  438. }
  439. break;
  440. }
  441. }
  442. output.AppendCount (maxJsonLength, "\"");
  443. }
  444. }
  445. }