JsonMapper.cs 31 KB

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