JsonMapper.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. #region Header
  2. /**
  3. * JsonMapper.cs
  4. * JSON to .Net object and object to JSON conversions.
  5. *
  6. * The authors disclaim copyright to this source code. For more details, see
  7. * the COPYING file included with this distribution.
  8. **/
  9. #endregion
  10. using System;
  11. using System.Collections;
  12. using System.Collections.Generic;
  13. using System.Globalization;
  14. using System.IO;
  15. using System.Reflection;
  16. namespace XGame.LitJson
  17. {
  18. internal struct PropertyMetadata
  19. {
  20. public MemberInfo Info;
  21. public bool IsField;
  22. public Type Type;
  23. }
  24. internal struct ArrayMetadata
  25. {
  26. private Type element_type;
  27. private bool is_array;
  28. private bool is_list;
  29. public Type ElementType {
  30. get {
  31. if (element_type == null)
  32. return typeof (JsonData);
  33. return element_type;
  34. }
  35. set { element_type = value; }
  36. }
  37. public bool IsArray {
  38. get { return is_array; }
  39. set { is_array = value; }
  40. }
  41. public bool IsList {
  42. get { return is_list; }
  43. set { is_list = value; }
  44. }
  45. }
  46. internal struct ObjectMetadata
  47. {
  48. private Type element_type;
  49. private bool is_dictionary;
  50. private IDictionary<string, PropertyMetadata> properties;
  51. public Type ElementType {
  52. get {
  53. if (element_type == null)
  54. return typeof (JsonData);
  55. return element_type;
  56. }
  57. set { element_type = value; }
  58. }
  59. public bool IsDictionary {
  60. get { return is_dictionary; }
  61. set { is_dictionary = value; }
  62. }
  63. public IDictionary<string, PropertyMetadata> Properties {
  64. get { return properties; }
  65. set { properties = value; }
  66. }
  67. }
  68. internal delegate void ExporterFunc (object obj, JsonWriter writer);
  69. public delegate void ExporterFunc<T> (T obj, JsonWriter writer);
  70. internal delegate object ImporterFunc (object input);
  71. public delegate TValue ImporterFunc<TJson, TValue> (TJson input);
  72. public delegate IJsonWrapper WrapperFactory ();
  73. /// <summary>
  74. /// 命名空间改为XGame.LitJson
  75. /// 避免和微信sdk内置的LitJson冲突
  76. /// </summary>
  77. public class JsonMapper
  78. {
  79. #region Fields
  80. private static readonly int max_nesting_depth;
  81. private static readonly IFormatProvider datetime_format;
  82. private static readonly IDictionary<Type, ExporterFunc> base_exporters_table;
  83. private static readonly IDictionary<Type, ExporterFunc> custom_exporters_table;
  84. private static readonly IDictionary<Type,
  85. IDictionary<Type, ImporterFunc>> base_importers_table;
  86. private static readonly IDictionary<Type,
  87. IDictionary<Type, ImporterFunc>> custom_importers_table;
  88. private static readonly IDictionary<Type, ArrayMetadata> array_metadata;
  89. private static readonly object array_metadata_lock = new Object ();
  90. private static readonly IDictionary<Type,
  91. IDictionary<Type, MethodInfo>> conv_ops;
  92. private static readonly object conv_ops_lock = new Object ();
  93. private static readonly IDictionary<Type, ObjectMetadata> object_metadata;
  94. private static readonly object object_metadata_lock = new Object ();
  95. private static readonly IDictionary<Type,
  96. IList<PropertyMetadata>> type_properties;
  97. private static readonly object type_properties_lock = new Object ();
  98. private static readonly JsonWriter static_writer;
  99. private static readonly object static_writer_lock = new Object ();
  100. #endregion
  101. #region Constructors
  102. static JsonMapper ()
  103. {
  104. max_nesting_depth = 100;
  105. array_metadata = new Dictionary<Type, ArrayMetadata> ();
  106. conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> ();
  107. object_metadata = new Dictionary<Type, ObjectMetadata> ();
  108. type_properties = new Dictionary<Type,
  109. IList<PropertyMetadata>> ();
  110. static_writer = new JsonWriter ();
  111. datetime_format = DateTimeFormatInfo.InvariantInfo;
  112. base_exporters_table = new Dictionary<Type, ExporterFunc> ();
  113. custom_exporters_table = new Dictionary<Type, ExporterFunc> ();
  114. base_importers_table = new Dictionary<Type,
  115. IDictionary<Type, ImporterFunc>> ();
  116. custom_importers_table = new Dictionary<Type,
  117. IDictionary<Type, ImporterFunc>> ();
  118. RegisterBaseExporters ();
  119. RegisterBaseImporters ();
  120. }
  121. #endregion
  122. #region Private Methods
  123. private static void AddArrayMetadata (Type type)
  124. {
  125. if (array_metadata.ContainsKey (type))
  126. return;
  127. ArrayMetadata data = new ArrayMetadata ();
  128. data.IsArray = type.IsArray;
  129. if (type.GetInterface ("System.Collections.IList") != null)
  130. data.IsList = true;
  131. foreach (PropertyInfo p_info in type.GetProperties ()) {
  132. if (p_info.Name != "Item")
  133. continue;
  134. ParameterInfo[] parameters = p_info.GetIndexParameters ();
  135. if (parameters.Length != 1)
  136. continue;
  137. if (parameters[0].ParameterType == typeof (int))
  138. data.ElementType = p_info.PropertyType;
  139. }
  140. lock (array_metadata_lock) {
  141. try {
  142. array_metadata.Add (type, data);
  143. } catch (ArgumentException) {
  144. return;
  145. }
  146. }
  147. }
  148. private static void AddObjectMetadata (Type type)
  149. {
  150. if (object_metadata.ContainsKey (type))
  151. return;
  152. ObjectMetadata data = new ObjectMetadata ();
  153. if (type.GetInterface ("System.Collections.IDictionary") != null)
  154. data.IsDictionary = true;
  155. data.Properties = new Dictionary<string, PropertyMetadata> ();
  156. foreach (PropertyInfo p_info in type.GetProperties ()) {
  157. if (p_info.Name == "Item") {
  158. ParameterInfo[] parameters = p_info.GetIndexParameters ();
  159. if (parameters.Length != 1)
  160. continue;
  161. if (parameters[0].ParameterType == typeof (string))
  162. data.ElementType = p_info.PropertyType;
  163. continue;
  164. }
  165. PropertyMetadata p_data = new PropertyMetadata ();
  166. p_data.Info = p_info;
  167. p_data.Type = p_info.PropertyType;
  168. data.Properties.Add (p_info.Name, p_data);
  169. }
  170. foreach (FieldInfo f_info in type.GetFields ()) {
  171. PropertyMetadata p_data = new PropertyMetadata ();
  172. p_data.Info = f_info;
  173. p_data.IsField = true;
  174. p_data.Type = f_info.FieldType;
  175. data.Properties.Add (f_info.Name, p_data);
  176. }
  177. lock (object_metadata_lock) {
  178. try {
  179. object_metadata.Add (type, data);
  180. } catch (ArgumentException) {
  181. return;
  182. }
  183. }
  184. }
  185. private static void AddTypeProperties (Type type)
  186. {
  187. if (type_properties.ContainsKey (type))
  188. return;
  189. IList<PropertyMetadata> props = new List<PropertyMetadata> ();
  190. foreach (PropertyInfo p_info in type.GetProperties()) {
  191. if (p_info.Name == "Item")
  192. continue;
  193. PropertyMetadata p_data = new PropertyMetadata();
  194. p_data.Info = p_info;
  195. p_data.IsField = false;
  196. props.Add(p_data);
  197. }
  198. foreach (FieldInfo f_info in type.GetFields ()) {
  199. PropertyMetadata p_data = new PropertyMetadata ();
  200. p_data.Info = f_info;
  201. p_data.IsField = true;
  202. props.Add (p_data);
  203. }
  204. lock (type_properties_lock) {
  205. try {
  206. type_properties.Add (type, props);
  207. } catch (ArgumentException) {
  208. return;
  209. }
  210. }
  211. }
  212. private static MethodInfo GetConvOp (Type t1, Type t2)
  213. {
  214. lock (conv_ops_lock) {
  215. if (! conv_ops.ContainsKey (t1))
  216. conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ());
  217. }
  218. if (conv_ops[t1].ContainsKey (t2))
  219. return conv_ops[t1][t2];
  220. MethodInfo op = t1.GetMethod (
  221. "op_Implicit", new Type[] { t2 });
  222. lock (conv_ops_lock) {
  223. try {
  224. conv_ops[t1].Add (t2, op);
  225. } catch (ArgumentException) {
  226. return conv_ops[t1][t2];
  227. }
  228. }
  229. return op;
  230. }
  231. private static object ReadValue (Type inst_type, JsonReader reader)
  232. {
  233. reader.Read ();
  234. if (reader.Token == JsonToken.ArrayEnd)
  235. return null;
  236. Type underlying_type = Nullable.GetUnderlyingType(inst_type);
  237. Type value_type = underlying_type ?? inst_type;
  238. if (reader.Token == JsonToken.Null) {
  239. #if NETSTANDARD1_5
  240. if (inst_type.IsClass() || underlying_type != null) {
  241. return null;
  242. }
  243. #else
  244. if (inst_type.IsClass || underlying_type != null) {
  245. return null;
  246. }
  247. #endif
  248. throw new JsonException (String.Format (
  249. "Can't assign null to an instance of type {0}",
  250. inst_type));
  251. }
  252. if (reader.Token == JsonToken.Double ||
  253. reader.Token == JsonToken.Int ||
  254. reader.Token == JsonToken.Long ||
  255. reader.Token == JsonToken.String ||
  256. reader.Token == JsonToken.Boolean) {
  257. Type json_type = reader.Value.GetType ();
  258. if (value_type.IsAssignableFrom (json_type))
  259. return reader.Value;
  260. if (value_type == typeof(float) && json_type == typeof(double))
  261. {
  262. float v = Convert.ToSingle(reader.Value);
  263. return v;
  264. }
  265. // If there's a custom importer that fits, use it
  266. if (custom_importers_table.ContainsKey (json_type) &&
  267. custom_importers_table[json_type].ContainsKey (
  268. value_type)) {
  269. ImporterFunc importer =
  270. custom_importers_table[json_type][value_type];
  271. return importer (reader.Value);
  272. }
  273. // Maybe there's a base importer that works
  274. if (base_importers_table.ContainsKey (json_type) &&
  275. base_importers_table[json_type].ContainsKey (
  276. value_type)) {
  277. ImporterFunc importer =
  278. base_importers_table[json_type][value_type];
  279. return importer (reader.Value);
  280. }
  281. // Maybe it's an enum
  282. #if NETSTANDARD1_5
  283. if (value_type.IsEnum())
  284. return Enum.ToObject (value_type, reader.Value);
  285. #else
  286. if (value_type.IsEnum)
  287. return Enum.ToObject (value_type, reader.Value);
  288. #endif
  289. // Try using an implicit conversion operator
  290. MethodInfo conv_op = GetConvOp (value_type, json_type);
  291. if (conv_op != null)
  292. return conv_op.Invoke (null,
  293. new object[] { reader.Value });
  294. // No luck
  295. throw new JsonException (String.Format (
  296. "Can't assign value '{0}' (type {1}) to type {2}",
  297. reader.Value, json_type, inst_type));
  298. }
  299. object instance = null;
  300. if (reader.Token == JsonToken.ArrayStart) {
  301. AddArrayMetadata (inst_type);
  302. ArrayMetadata t_data = array_metadata[inst_type];
  303. if (! t_data.IsArray && ! t_data.IsList)
  304. throw new JsonException (String.Format (
  305. "Type {0} can't act as an array",
  306. inst_type));
  307. IList list;
  308. Type elem_type;
  309. if (! t_data.IsArray) {
  310. list = (IList) Activator.CreateInstance (inst_type);
  311. elem_type = t_data.ElementType;
  312. } else {
  313. list = new ArrayList ();
  314. elem_type = inst_type.GetElementType ();
  315. }
  316. while (true) {
  317. object item = ReadValue (elem_type, reader);
  318. if (item == null && reader.Token == JsonToken.ArrayEnd)
  319. break;
  320. list.Add (item);
  321. }
  322. if (t_data.IsArray) {
  323. int n = list.Count;
  324. instance = Array.CreateInstance (elem_type, n);
  325. for (int i = 0; i < n; i++)
  326. ((Array) instance).SetValue (list[i], i);
  327. } else
  328. instance = list;
  329. } else if (reader.Token == JsonToken.ObjectStart) {
  330. AddObjectMetadata (value_type);
  331. ObjectMetadata t_data = object_metadata[value_type];
  332. instance = Activator.CreateInstance (value_type);
  333. while (true) {
  334. reader.Read ();
  335. if (reader.Token == JsonToken.ObjectEnd)
  336. break;
  337. string property = (string) reader.Value;
  338. if (t_data.Properties.ContainsKey (property)) {
  339. PropertyMetadata prop_data =
  340. t_data.Properties[property];
  341. if (prop_data.IsField) {
  342. ((FieldInfo) prop_data.Info).SetValue (
  343. instance, ReadValue (prop_data.Type, reader));
  344. } else {
  345. PropertyInfo p_info =
  346. (PropertyInfo) prop_data.Info;
  347. if (p_info.CanWrite)
  348. p_info.SetValue (
  349. instance,
  350. ReadValue (prop_data.Type, reader),
  351. null);
  352. else
  353. ReadValue (prop_data.Type, reader);
  354. }
  355. } else {
  356. if (! t_data.IsDictionary) {
  357. if (! reader.SkipNonMembers) {
  358. throw new JsonException (String.Format (
  359. "The type {0} doesn't have the " +
  360. "property '{1}'",
  361. inst_type, property));
  362. } else {
  363. ReadSkip (reader);
  364. continue;
  365. }
  366. }
  367. ((IDictionary) instance).Add (
  368. property, ReadValue (
  369. t_data.ElementType, reader));
  370. }
  371. }
  372. }
  373. return instance;
  374. }
  375. private static IJsonWrapper ReadValue (WrapperFactory factory,
  376. JsonReader reader)
  377. {
  378. reader.Read ();
  379. if (reader.Token == JsonToken.ArrayEnd ||
  380. reader.Token == JsonToken.Null)
  381. return null;
  382. IJsonWrapper instance = factory ();
  383. if (reader.Token == JsonToken.String) {
  384. instance.SetString ((string) reader.Value);
  385. return instance;
  386. }
  387. if (reader.Token == JsonToken.Double) {
  388. instance.SetDouble ((double) reader.Value);
  389. return instance;
  390. }
  391. if (reader.Token == JsonToken.Int) {
  392. instance.SetInt ((int) reader.Value);
  393. return instance;
  394. }
  395. if (reader.Token == JsonToken.Long) {
  396. instance.SetLong ((long) reader.Value);
  397. return instance;
  398. }
  399. if (reader.Token == JsonToken.Boolean) {
  400. instance.SetBoolean ((bool) reader.Value);
  401. return instance;
  402. }
  403. if (reader.Token == JsonToken.ArrayStart) {
  404. instance.SetJsonType (JsonType.Array);
  405. while (true) {
  406. IJsonWrapper item = ReadValue (factory, reader);
  407. if (item == null && reader.Token == JsonToken.ArrayEnd)
  408. break;
  409. ((IList) instance).Add (item);
  410. }
  411. }
  412. else if (reader.Token == JsonToken.ObjectStart) {
  413. instance.SetJsonType (JsonType.Object);
  414. while (true) {
  415. reader.Read ();
  416. if (reader.Token == JsonToken.ObjectEnd)
  417. break;
  418. string property = (string) reader.Value;
  419. ((IDictionary) instance)[property] = ReadValue (
  420. factory, reader);
  421. }
  422. }
  423. return instance;
  424. }
  425. private static void ReadSkip (JsonReader reader)
  426. {
  427. ToWrapper (
  428. delegate { return new JsonMockWrapper (); }, reader);
  429. }
  430. private static void RegisterBaseExporters ()
  431. {
  432. base_exporters_table[typeof (byte)] =
  433. delegate (object obj, JsonWriter writer) {
  434. writer.Write (Convert.ToInt32 ((byte) obj));
  435. };
  436. base_exporters_table[typeof (char)] =
  437. delegate (object obj, JsonWriter writer) {
  438. writer.Write (Convert.ToString ((char) obj));
  439. };
  440. base_exporters_table[typeof (DateTime)] =
  441. delegate (object obj, JsonWriter writer) {
  442. writer.Write (Convert.ToString ((DateTime) obj,
  443. datetime_format));
  444. };
  445. base_exporters_table[typeof (decimal)] =
  446. delegate (object obj, JsonWriter writer) {
  447. writer.Write ((decimal) obj);
  448. };
  449. base_exporters_table[typeof (sbyte)] =
  450. delegate (object obj, JsonWriter writer) {
  451. writer.Write (Convert.ToInt32 ((sbyte) obj));
  452. };
  453. base_exporters_table[typeof (short)] =
  454. delegate (object obj, JsonWriter writer) {
  455. writer.Write (Convert.ToInt32 ((short) obj));
  456. };
  457. base_exporters_table[typeof (ushort)] =
  458. delegate (object obj, JsonWriter writer) {
  459. writer.Write (Convert.ToInt32 ((ushort) obj));
  460. };
  461. base_exporters_table[typeof (uint)] =
  462. delegate (object obj, JsonWriter writer) {
  463. writer.Write (Convert.ToUInt64 ((uint) obj));
  464. };
  465. base_exporters_table[typeof (ulong)] =
  466. delegate (object obj, JsonWriter writer) {
  467. writer.Write ((ulong) obj);
  468. };
  469. }
  470. private static void RegisterBaseImporters ()
  471. {
  472. ImporterFunc importer;
  473. importer = delegate (object input) {
  474. return Convert.ToByte ((int) input);
  475. };
  476. RegisterImporter (base_importers_table, typeof (int),
  477. typeof (byte), importer);
  478. importer = delegate (object input) {
  479. return Convert.ToUInt64 ((int) input);
  480. };
  481. RegisterImporter (base_importers_table, typeof (int),
  482. typeof (ulong), importer);
  483. importer = delegate (object input) {
  484. return Convert.ToInt64((int)input);
  485. };
  486. RegisterImporter(base_importers_table, typeof(int),
  487. typeof(long), importer);
  488. importer = delegate (object input) {
  489. return Convert.ToSByte ((int) input);
  490. };
  491. RegisterImporter (base_importers_table, typeof (int),
  492. typeof (sbyte), importer);
  493. importer = delegate (object input) {
  494. return Convert.ToInt16 ((int) input);
  495. };
  496. RegisterImporter (base_importers_table, typeof (int),
  497. typeof (short), importer);
  498. importer = delegate (object input) {
  499. return Convert.ToUInt16 ((int) input);
  500. };
  501. RegisterImporter (base_importers_table, typeof (int),
  502. typeof (ushort), importer);
  503. importer = delegate (object input) {
  504. return Convert.ToUInt32 ((int) input);
  505. };
  506. RegisterImporter (base_importers_table, typeof (int),
  507. typeof (uint), importer);
  508. importer = delegate (object input) {
  509. return Convert.ToSingle ((int) input);
  510. };
  511. RegisterImporter (base_importers_table, typeof (int),
  512. typeof (float), importer);
  513. importer = delegate (object input) {
  514. return Convert.ToDouble ((int) input);
  515. };
  516. RegisterImporter (base_importers_table, typeof (int),
  517. typeof (double), importer);
  518. importer = delegate (object input) {
  519. return Convert.ToDecimal ((double) input);
  520. };
  521. RegisterImporter (base_importers_table, typeof (double),
  522. typeof (decimal), importer);
  523. importer = delegate (object input) {
  524. return Convert.ToUInt32 ((long) input);
  525. };
  526. RegisterImporter (base_importers_table, typeof (long),
  527. typeof (uint), importer);
  528. importer = delegate (object input) {
  529. return Convert.ToChar ((string) input);
  530. };
  531. RegisterImporter (base_importers_table, typeof (string),
  532. typeof (char), importer);
  533. importer = delegate (object input) {
  534. return Convert.ToDateTime ((string) input, datetime_format);
  535. };
  536. RegisterImporter (base_importers_table, typeof (string),
  537. typeof (DateTime), importer);
  538. importer = delegate (object input) {
  539. return DateTimeOffset.Parse((string)input, datetime_format);
  540. };
  541. RegisterImporter(base_importers_table, typeof(string),
  542. typeof(DateTimeOffset), importer);
  543. }
  544. private static void RegisterImporter (
  545. IDictionary<Type, IDictionary<Type, ImporterFunc>> table,
  546. Type json_type, Type value_type, ImporterFunc importer)
  547. {
  548. if (! table.ContainsKey (json_type))
  549. table.Add (json_type, new Dictionary<Type, ImporterFunc> ());
  550. table[json_type][value_type] = importer;
  551. }
  552. private static void WriteValue (object obj, JsonWriter writer,
  553. bool writer_is_private,
  554. int depth)
  555. {
  556. if (depth > max_nesting_depth)
  557. throw new JsonException (
  558. String.Format ("Max allowed object depth reached while " +
  559. "trying to export from type {0}",
  560. obj.GetType ()));
  561. if (obj == null) {
  562. writer.Write (null);
  563. return;
  564. }
  565. if (obj is IJsonWrapper jsonwrapper) {
  566. if (writer_is_private)
  567. writer.WriteJsonWrapper(jsonwrapper);
  568. else
  569. ((IJsonWrapper) obj).ToJson (writer);
  570. return;
  571. }
  572. if (obj is String) {
  573. writer.Write ((string) obj);
  574. return;
  575. }
  576. if (obj is Single)
  577. {
  578. writer.Write ((float) obj);
  579. return;
  580. }
  581. if (obj is Double) {
  582. writer.Write ((double) obj);
  583. return;
  584. }
  585. if (obj is Int32) {
  586. writer.Write ((int) obj);
  587. return;
  588. }
  589. if (obj is Boolean) {
  590. writer.Write ((bool) obj);
  591. return;
  592. }
  593. if (obj is Int64) {
  594. writer.Write ((long) obj);
  595. return;
  596. }
  597. if (obj is Array) {
  598. writer.WriteArrayStart ();
  599. foreach (object elem in (Array) obj)
  600. WriteValue (elem, writer, writer_is_private, depth + 1);
  601. writer.WriteArrayEnd ();
  602. return;
  603. }
  604. if (obj is IList) {
  605. writer.WriteArrayStart ();
  606. foreach (object elem in (IList)obj)
  607. WriteValue(elem, writer, writer_is_private, depth + 1);
  608. writer.WriteArrayEnd ();
  609. return;
  610. }
  611. if (obj is IDictionary) {
  612. writer.WriteObjectStart ();
  613. foreach (DictionaryEntry entry in (IDictionary) obj) {
  614. writer.WritePropertyName ((string) entry.Key);
  615. WriteValue (entry.Value, writer, writer_is_private,
  616. depth + 1);
  617. }
  618. writer.WriteObjectEnd ();
  619. return;
  620. }
  621. Type obj_type = obj.GetType ();
  622. // See if there's a custom exporter for the object
  623. if (custom_exporters_table.ContainsKey (obj_type)) {
  624. ExporterFunc exporter = custom_exporters_table[obj_type];
  625. exporter (obj, writer);
  626. return;
  627. }
  628. // If not, maybe there's a base exporter
  629. if (base_exporters_table.ContainsKey (obj_type)) {
  630. ExporterFunc exporter = base_exporters_table[obj_type];
  631. exporter (obj, writer);
  632. return;
  633. }
  634. // Last option, let's see if it's an enum
  635. if (obj is Enum) {
  636. Type e_type = Enum.GetUnderlyingType (obj_type);
  637. if (e_type == typeof (long)
  638. || e_type == typeof (uint)
  639. || e_type == typeof (ulong))
  640. writer.Write ((ulong) obj);
  641. else
  642. writer.Write ((int) obj);
  643. return;
  644. }
  645. // Okay, so it looks like the input should be exported as an
  646. // object
  647. AddTypeProperties (obj_type);
  648. IList<PropertyMetadata> props = type_properties[obj_type];
  649. writer.WriteObjectStart ();
  650. foreach (PropertyMetadata p_data in props) {
  651. if (p_data.IsField) {
  652. writer.WritePropertyName (p_data.Info.Name);
  653. WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
  654. writer, writer_is_private, depth + 1);
  655. }
  656. else {
  657. PropertyInfo p_info = (PropertyInfo) p_data.Info;
  658. if (p_info.CanRead) {
  659. writer.WritePropertyName (p_data.Info.Name);
  660. WriteValue (p_info.GetValue (obj, null),
  661. writer, writer_is_private, depth + 1);
  662. }
  663. }
  664. }
  665. writer.WriteObjectEnd ();
  666. }
  667. #endregion
  668. public static string ToJson (object obj)
  669. {
  670. lock (static_writer_lock) {
  671. static_writer.Reset ();
  672. WriteValue (obj, static_writer, true, 0);
  673. return static_writer.ToString ();
  674. }
  675. }
  676. public static void ToJson (object obj, JsonWriter writer)
  677. {
  678. WriteValue (obj, writer, false, 0);
  679. }
  680. public static JsonData ToObject (JsonReader reader)
  681. {
  682. return (JsonData) ToWrapper (
  683. delegate { return new JsonData (); }, reader);
  684. }
  685. public static JsonData ToObject (TextReader reader)
  686. {
  687. JsonReader json_reader = new JsonReader (reader);
  688. return (JsonData) ToWrapper (
  689. delegate { return new JsonData (); }, json_reader);
  690. }
  691. public static JsonData ToObject (string json)
  692. {
  693. return (JsonData) ToWrapper (
  694. delegate { return new JsonData (); }, json);
  695. }
  696. public static T ToObject<T> (JsonReader reader)
  697. {
  698. return (T) ReadValue (typeof (T), reader);
  699. }
  700. public static T ToObject<T> (TextReader reader)
  701. {
  702. JsonReader json_reader = new JsonReader (reader);
  703. return (T) ReadValue (typeof (T), json_reader);
  704. }
  705. public static T ToObject<T> (string json)
  706. {
  707. JsonReader reader = new JsonReader (json);
  708. return (T) ReadValue (typeof (T), reader);
  709. }
  710. public static object ToObject(string json, Type ConvertType )
  711. {
  712. JsonReader reader = new JsonReader(json);
  713. return ReadValue(ConvertType, reader);
  714. }
  715. public static IJsonWrapper ToWrapper (WrapperFactory factory,
  716. JsonReader reader)
  717. {
  718. return ReadValue (factory, reader);
  719. }
  720. public static IJsonWrapper ToWrapper (WrapperFactory factory,
  721. string json)
  722. {
  723. JsonReader reader = new JsonReader (json);
  724. return ReadValue (factory, reader);
  725. }
  726. public static void RegisterExporter<T> (ExporterFunc<T> exporter)
  727. {
  728. ExporterFunc exporter_wrapper =
  729. delegate (object obj, JsonWriter writer) {
  730. exporter ((T) obj, writer);
  731. };
  732. custom_exporters_table[typeof (T)] = exporter_wrapper;
  733. }
  734. public static void RegisterImporter<TJson, TValue> (
  735. ImporterFunc<TJson, TValue> importer)
  736. {
  737. ImporterFunc importer_wrapper =
  738. delegate (object input) {
  739. return importer ((TJson) input);
  740. };
  741. RegisterImporter (custom_importers_table, typeof (TJson),
  742. typeof (TValue), importer_wrapper);
  743. }
  744. public static void UnregisterExporters ()
  745. {
  746. custom_exporters_table.Clear ();
  747. }
  748. public static void UnregisterImporters ()
  749. {
  750. custom_importers_table.Clear ();
  751. }
  752. }
  753. }