JsonSerializer.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. StringBuilderExtensions.AppendCount (output, 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. StringBuilderExtensions.AppendCount (output, 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 == null)
  205. return true;
  206. if (mi.IsDefined (typeof (ScriptIgnoreAttribute), true))
  207. return true;
  208. FieldInfo fi = mi as FieldInfo;
  209. if (fi != null)
  210. return false;
  211. PropertyInfo pi = mi as PropertyInfo;
  212. if (pi == null)
  213. return true;
  214. getMethod = pi.GetGetMethod ();
  215. if (getMethod == null || getMethod.GetParameters ().Length > 0) {
  216. getMethod = null;
  217. return true;
  218. }
  219. return false;
  220. }
  221. object GetMemberValue (object obj, MemberInfo mi)
  222. {
  223. FieldInfo fi = mi as FieldInfo;
  224. if (fi != null)
  225. return fi.GetValue (obj);
  226. MethodInfo method = mi as MethodInfo;
  227. if (method == null)
  228. throw new InvalidOperationException ("Member is not a method (internal error).");
  229. object ret;
  230. try {
  231. ret = method.Invoke (obj, null);
  232. } catch (TargetInvocationException niex) {
  233. if (niex.InnerException is NotImplementedException) {
  234. Console.WriteLine ("!!! COMPATIBILITY WARNING. FEATURE NOT IMPLEMENTED. !!!");
  235. Console.WriteLine (niex);
  236. Console.WriteLine ("!!! RETURNING NULL. PLEASE LET MONO DEVELOPERS KNOW ABOUT THIS EXCEPTION. !!!");
  237. return null;
  238. }
  239. throw;
  240. }
  241. return ret;
  242. }
  243. void SerializeArbitraryObject (StringBuilder output, object obj, Type type)
  244. {
  245. StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
  246. bool first = true;
  247. if (typeResolver != null) {
  248. string typeId = typeResolver.ResolveTypeId (type);
  249. if (!String.IsNullOrEmpty (typeId)) {
  250. WriteDictionaryEntry (output, first, JavaScriptSerializer.SerializedTypeNameKey, typeId);
  251. first = false;
  252. }
  253. }
  254. SerializeMembers <FieldInfo> (type.GetFields (BindingFlags.Public | BindingFlags.Instance), obj, output, ref first);
  255. SerializeMembers <PropertyInfo> (type.GetProperties (BindingFlags.Public | BindingFlags.Instance), obj, output, ref first);
  256. StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
  257. }
  258. void SerializeMembers <T> (T[] members, object obj, StringBuilder output, ref bool first) where T: MemberInfo
  259. {
  260. MemberInfo member;
  261. MethodInfo getMethod;
  262. string name;
  263. foreach (T mi in members) {
  264. if (ShouldIgnoreMember (mi as MemberInfo, out getMethod))
  265. continue;
  266. name = mi.Name;
  267. if (getMethod != null)
  268. member = getMethod;
  269. else
  270. member = mi;
  271. WriteDictionaryEntry (output, first, name, GetMemberValue (obj, member));
  272. if (first)
  273. first = false;
  274. }
  275. }
  276. void SerializeEnumerable (StringBuilder output, IEnumerable enumerable)
  277. {
  278. StringBuilderExtensions.AppendCount (output, maxJsonLength, "[");
  279. bool first = true;
  280. foreach (object value in enumerable) {
  281. if (!first)
  282. StringBuilderExtensions.AppendCount (output, maxJsonLength, ',');
  283. SerializeValue (value, output);
  284. if (first)
  285. first = false;
  286. }
  287. StringBuilderExtensions.AppendCount (output, maxJsonLength, "]");
  288. }
  289. void SerializeDictionary (StringBuilder output, IDictionary dict)
  290. {
  291. StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
  292. bool first = true;
  293. foreach (DictionaryEntry entry in dict) {
  294. WriteDictionaryEntry (output, first, entry.Key as string, entry.Value);
  295. if (first)
  296. first = false;
  297. }
  298. StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
  299. }
  300. void SerializeGenericDictionary <TKey, TValue> (StringBuilder output, IDictionary <TKey, TValue> dict)
  301. {
  302. StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
  303. bool first = true;
  304. foreach (KeyValuePair <TKey, TValue> kvp in dict) {
  305. WriteDictionaryEntry (output, first, kvp.Key as string, kvp.Value);
  306. if (first)
  307. first = false;
  308. }
  309. StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
  310. }
  311. void WriteDictionaryEntry (StringBuilder output, bool skipComma, string key, object value)
  312. {
  313. if (key == null)
  314. throw new InvalidOperationException ("Only dictionaries with keys convertible to string are supported.");
  315. if (!skipComma)
  316. StringBuilderExtensions.AppendCount (output, maxJsonLength, ',');
  317. WriteValue (output, key);
  318. StringBuilderExtensions.AppendCount (output, maxJsonLength, ':');
  319. SerializeValue (value, output);
  320. }
  321. void WriteEnumValue (StringBuilder output, object value, TypeCode typeCode)
  322. {
  323. switch (typeCode) {
  324. case TypeCode.SByte:
  325. StringBuilderExtensions.AppendCount (output, maxJsonLength, (sbyte)value);
  326. return;
  327. case TypeCode.Int16:
  328. StringBuilderExtensions.AppendCount (output, maxJsonLength, (short)value);
  329. return;
  330. case TypeCode.UInt16:
  331. StringBuilderExtensions.AppendCount (output, maxJsonLength, (ushort)value);
  332. return;
  333. case TypeCode.Int32:
  334. StringBuilderExtensions.AppendCount (output, maxJsonLength, (int)value);
  335. return;
  336. case TypeCode.Byte:
  337. StringBuilderExtensions.AppendCount (output, maxJsonLength, (byte)value);
  338. return;
  339. case TypeCode.UInt32:
  340. StringBuilderExtensions.AppendCount (output, maxJsonLength, (uint)value);
  341. return;
  342. case TypeCode.Int64:
  343. StringBuilderExtensions.AppendCount (output, maxJsonLength, (long)value);
  344. return;
  345. case TypeCode.UInt64:
  346. StringBuilderExtensions.AppendCount (output, maxJsonLength, (ulong)value);
  347. return;
  348. default:
  349. throw new InvalidOperationException (String.Format ("Invalid type code for enum: {0}", typeCode));
  350. }
  351. }
  352. void WriteValue (StringBuilder output, float value)
  353. {
  354. StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString ("r", CultureInfo.InvariantCulture));
  355. }
  356. void WriteValue (StringBuilder output, double value)
  357. {
  358. StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString ("r", CultureInfo.InvariantCulture));
  359. }
  360. void WriteValue (StringBuilder output, Guid value)
  361. {
  362. WriteValue (output, value.ToString ());
  363. }
  364. void WriteValue (StringBuilder output, Uri value)
  365. {
  366. WriteValue (output, value.OriginalString);
  367. }
  368. void WriteValue (StringBuilder output, DateTime value)
  369. {
  370. value = value.ToUniversalTime ();
  371. if (value < MinimumJavaScriptDate)
  372. value = MinimumJavaScriptDate;
  373. long ticks = (value.Ticks - InitialJavaScriptDateTicks) / (long)10000;
  374. StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"\\/Date(" + ticks + ")\\/\"");
  375. }
  376. void WriteValue (StringBuilder output, IConvertible value)
  377. {
  378. StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString (CultureInfo.InvariantCulture));
  379. }
  380. void WriteValue (StringBuilder output, bool value)
  381. {
  382. StringBuilderExtensions.AppendCount (output, maxJsonLength, value ? "true" : "false");
  383. }
  384. void WriteValue (StringBuilder output, char value)
  385. {
  386. if (value == '\0') {
  387. StringBuilderExtensions.AppendCount (output, maxJsonLength, "null");
  388. return;
  389. }
  390. WriteValue (output, value.ToString ());
  391. }
  392. void WriteValue (StringBuilder output, string value)
  393. {
  394. if (String.IsNullOrEmpty (value)) {
  395. StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"\"");
  396. return;
  397. }
  398. StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"");
  399. char c;
  400. for (int i = 0; i < value.Length; i++) {
  401. c = value [i];
  402. switch (c) {
  403. case '\t':
  404. StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\t");
  405. break;
  406. case '\n':
  407. StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\n");
  408. break;
  409. case '\r':
  410. StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\r");
  411. break;
  412. case '\f':
  413. StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\f");
  414. break;
  415. case '\b':
  416. StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\b");
  417. break;
  418. case '<':
  419. StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u003c");
  420. break;
  421. case '>':
  422. StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u003e");
  423. break;
  424. case '"':
  425. StringBuilderExtensions.AppendCount (output, maxJsonLength, "\\\"");
  426. break;
  427. case '\'':
  428. StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u0027");
  429. break;
  430. case '\\':
  431. StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\\");
  432. break;
  433. default:
  434. if (c > '\u001f')
  435. StringBuilderExtensions.AppendCount (output, maxJsonLength, c);
  436. else {
  437. output.Append("\\u00");
  438. int intVal = (int) c;
  439. StringBuilderExtensions.AppendCount (output, maxJsonLength, (char) ('0' + (intVal >> 4)));
  440. intVal &= 0xf;
  441. StringBuilderExtensions.AppendCount (output, maxJsonLength, (char) (intVal < 10 ? '0' + intVal : 'a' + (intVal - 10)));
  442. }
  443. break;
  444. }
  445. }
  446. StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"");
  447. }
  448. }
  449. }