JSON.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Reflection;
  8. public class JSON
  9. {
  10. private struct myPropInfo
  11. {
  12. public bool filled;
  13. public Type pt;
  14. public Type bt;
  15. public Type changeType;
  16. public bool isDictionary;
  17. public bool isValueType;
  18. public bool isGenericType;
  19. public bool isArray;
  20. public bool isByteArray;
  21. public bool isGuid;
  22. public bool isDataSet;
  23. public bool isDataTable;
  24. public bool isHashtable;
  25. public Reflection.GenericSetter setter;
  26. public bool isEnum;
  27. public bool isDateTime;
  28. public Type[] GenericTypes;
  29. public bool isInt;
  30. public bool isLong;
  31. public bool isString;
  32. public bool isBool;
  33. public bool isClass;
  34. public Reflection.GenericGetter getter;
  35. public bool isStringDictionary;
  36. public string Name;
  37. public bool CanWrite;
  38. }
  39. public static readonly JSON Instance = new JSON();
  40. public JSONParameters Parameters = new JSONParameters();
  41. private JSONParameters _params;
  42. private SafeDictionary<string, SafeDictionary<string, myPropInfo>> _propertycache = new SafeDictionary<string, SafeDictionary<string, myPropInfo>>();
  43. private bool usingglobals = false;
  44. private JSON()
  45. {
  46. }
  47. public string ToJSON(object obj)
  48. {
  49. _params = Parameters;
  50. Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties;
  51. return ToJSON(obj, Parameters);
  52. }
  53. public string ToJSON(object obj, JSONParameters param)
  54. {
  55. _params = param;
  56. Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties;
  57. if (_params.EnableAnonymousTypes)
  58. {
  59. _params.UseExtensions = false;
  60. _params.UsingGlobalTypes = false;
  61. }
  62. return new JSONSerializer(param).ConvertToJSON(obj);
  63. }
  64. public object Parse(string json)
  65. {
  66. _params = Parameters;
  67. Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties;
  68. return new JsonParser(json, Parameters.IgnoreCaseOnDeserialize).Decode();
  69. }
  70. public T ToObject<T>(string json)
  71. {
  72. return (T)ToObject(json, typeof(T));
  73. }
  74. public object ToObject(string json)
  75. {
  76. return ToObject(json, null);
  77. }
  78. public object ToObject(string json, Type type)
  79. {
  80. _params = Parameters;
  81. Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties;
  82. Dictionary<string, object> ht = new JsonParser(json, Parameters.IgnoreCaseOnDeserialize).Decode() as Dictionary<string, object>;
  83. if (ht == null)
  84. {
  85. return null;
  86. }
  87. return ParseDictionary(ht, null, type, null);
  88. }
  89. public string Beautify(string input)
  90. {
  91. return Formatter.PrettyPrint(input);
  92. }
  93. public object FillObject(object input, string json)
  94. {
  95. _params = Parameters;
  96. Reflection.Instance.ShowReadOnlyProperties = _params.ShowReadOnlyProperties;
  97. Dictionary<string, object> ht = new JsonParser(json, Parameters.IgnoreCaseOnDeserialize).Decode() as Dictionary<string, object>;
  98. if (ht == null)
  99. {
  100. return null;
  101. }
  102. return ParseDictionary(ht, null, input.GetType(), input);
  103. }
  104. public object DeepCopy(object obj)
  105. {
  106. return ToObject(ToJSON(obj));
  107. }
  108. public T DeepCopy<T>(T obj)
  109. {
  110. return ToObject<T>(ToJSON(obj));
  111. }
  112. private SafeDictionary<string, myPropInfo> Getproperties(Type type, string typename)
  113. {
  114. SafeDictionary<string, myPropInfo> sd = null;
  115. if (_propertycache.TryGetValue(typename, out sd))
  116. {
  117. return sd;
  118. }
  119. sd = new SafeDictionary<string, myPropInfo>();
  120. PropertyInfo[] pr = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
  121. PropertyInfo[] array = pr;
  122. foreach (PropertyInfo p in array)
  123. {
  124. myPropInfo d = CreateMyProp(p.PropertyType, p.Name);
  125. d.CanWrite = p.CanWrite;
  126. d.setter = Reflection.CreateSetMethod(type, p);
  127. d.getter = Reflection.CreateGetMethod(type, p);
  128. sd.Add(p.Name, d);
  129. }
  130. FieldInfo[] fi = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
  131. FieldInfo[] array2 = fi;
  132. foreach (FieldInfo f in array2)
  133. {
  134. myPropInfo d2 = CreateMyProp(f.FieldType, f.Name);
  135. d2.setter = Reflection.CreateSetField(type, f);
  136. d2.getter = Reflection.CreateGetField(type, f);
  137. sd.Add(f.Name, d2);
  138. }
  139. _propertycache.Add(typename, sd);
  140. return sd;
  141. }
  142. private myPropInfo CreateMyProp(Type t, string name)
  143. {
  144. myPropInfo d = default(myPropInfo);
  145. d.filled = true;
  146. d.CanWrite = true;
  147. d.pt = t;
  148. d.Name = name;
  149. d.isDictionary = t.Name.Contains("Dictionary");
  150. if (d.isDictionary)
  151. {
  152. d.GenericTypes = t.GetGenericArguments();
  153. }
  154. d.isValueType = t.IsValueType;
  155. d.isGenericType = t.IsGenericType;
  156. d.isArray = t.IsArray;
  157. if (d.isArray)
  158. {
  159. d.bt = t.GetElementType();
  160. }
  161. if (d.isGenericType)
  162. {
  163. d.bt = t.GetGenericArguments()[0];
  164. }
  165. d.isByteArray = t == typeof(byte[]);
  166. d.isGuid = t == typeof(Guid) || t == typeof(Guid?);
  167. d.isHashtable = t == typeof(Hashtable);
  168. d.isDataSet = t == typeof(DataSet);
  169. d.isDataTable = t == typeof(DataTable);
  170. d.changeType = GetChangeType(t);
  171. d.isEnum = t.IsEnum;
  172. d.isDateTime = t == typeof(DateTime) || t == typeof(DateTime?);
  173. d.isInt = t == typeof(int) || t == typeof(int?);
  174. d.isLong = t == typeof(long) || t == typeof(long?);
  175. d.isString = t == typeof(string);
  176. d.isBool = t == typeof(bool) || t == typeof(bool?);
  177. d.isClass = t.IsClass;
  178. if (d.isDictionary && d.GenericTypes.Length != 0 && d.GenericTypes[0] == typeof(string))
  179. {
  180. d.isStringDictionary = true;
  181. }
  182. return d;
  183. }
  184. private object ChangeType(object value, Type conversionType)
  185. {
  186. if (conversionType == typeof(int))
  187. {
  188. return (int)CreateLong((string)value);
  189. }
  190. if (conversionType == typeof(long))
  191. {
  192. return CreateLong((string)value);
  193. }
  194. if (conversionType == typeof(string))
  195. {
  196. return (string)value;
  197. }
  198. if (conversionType == typeof(Guid))
  199. {
  200. return CreateGuid((string)value);
  201. }
  202. if (conversionType.IsEnum)
  203. {
  204. return CreateEnum(conversionType, (string)value);
  205. }
  206. return Convert.ChangeType(value, conversionType, CultureInfo.InvariantCulture);
  207. }
  208. private object ParseDictionary(Dictionary<string, object> d, Dictionary<string, object> globaltypes, Type type, object input)
  209. {
  210. object tn = "";
  211. if (d.TryGetValue("$types", out tn))
  212. {
  213. usingglobals = true;
  214. globaltypes = new Dictionary<string, object>();
  215. foreach (KeyValuePair<string, object> kv in (Dictionary<string, object>)tn)
  216. {
  217. globaltypes.Add((string)kv.Value, kv.Key);
  218. }
  219. }
  220. bool found = d.TryGetValue("$type", out tn);
  221. if (!found && type == typeof(object))
  222. {
  223. return CreateDataset(d, globaltypes);
  224. }
  225. if (found)
  226. {
  227. if (usingglobals)
  228. {
  229. object tname = "";
  230. if (globaltypes.TryGetValue((string)tn, out tname))
  231. {
  232. tn = tname;
  233. }
  234. }
  235. type = Reflection.Instance.GetTypeFromCache((string)tn);
  236. }
  237. if (type == null)
  238. {
  239. throw new Exception("Cannot determine type");
  240. }
  241. string typename = type.FullName;
  242. object o = input;
  243. if (o == null)
  244. {
  245. o = Reflection.Instance.FastCreateInstance(type);
  246. }
  247. SafeDictionary<string, myPropInfo> props = Getproperties(type, typename);
  248. foreach (string i in d.Keys)
  249. {
  250. string name = i;
  251. if (_params.IgnoreCaseOnDeserialize)
  252. {
  253. name = name.ToLower();
  254. }
  255. if (name == "$map")
  256. {
  257. ProcessMap(o, props, (Dictionary<string, object>)d[name]);
  258. }
  259. else
  260. {
  261. if (!props.TryGetValue(name, out var pi) || !pi.filled)
  262. {
  263. continue;
  264. }
  265. object v = d[name];
  266. if (v != null)
  267. {
  268. object oset = null;
  269. oset = (pi.isInt ? ((object)(int)CreateLong((string)v)) : (pi.isLong ? ((object)CreateLong((string)v)) : (pi.isString ? ((string)v) : (pi.isBool ? ((object)(bool)v) : ((pi.isGenericType && !pi.isValueType && !pi.isDictionary) ? CreateGenericList((ArrayList)v, pi.pt, pi.bt, globaltypes) : (pi.isByteArray ? Convert.FromBase64String((string)v) : ((pi.isArray && !pi.isValueType) ? CreateArray((ArrayList)v, pi.pt, pi.bt, globaltypes) : (pi.isGuid ? ((object)CreateGuid((string)v)) : (pi.isDataSet ? CreateDataset((Dictionary<string, object>)v, globaltypes) : (pi.isDataTable ? CreateDataTable((Dictionary<string, object>)v, globaltypes) : (pi.isStringDictionary ? CreateStringKeyDictionary((Dictionary<string, object>)v, pi.pt, pi.GenericTypes, globaltypes) : ((pi.isDictionary || pi.isHashtable) ? CreateDictionary((ArrayList)v, pi.pt, pi.GenericTypes, globaltypes) : (pi.isEnum ? CreateEnum(pi.pt, (string)v) : (pi.isDateTime ? ((object)CreateDateTime((string)v)) : ((pi.isClass && v is Dictionary<string, object>) ? ParseDictionary((Dictionary<string, object>)v, globaltypes, pi.pt, null) : (pi.isValueType ? ChangeType(v, pi.changeType) : ((!(v is ArrayList)) ? v : CreateArray((ArrayList)v, pi.pt, typeof(object), globaltypes))))))))))))))))));
  270. if (pi.CanWrite)
  271. {
  272. o = pi.setter(o, oset);
  273. }
  274. }
  275. }
  276. }
  277. return o;
  278. }
  279. private void ProcessMap(object obj, SafeDictionary<string, myPropInfo> props, Dictionary<string, object> dic)
  280. {
  281. foreach (KeyValuePair<string, object> kv in dic)
  282. {
  283. myPropInfo p = props[kv.Key];
  284. object o = p.getter(obj);
  285. Type t = Type.GetType((string)kv.Value);
  286. if (t == typeof(Guid))
  287. {
  288. p.setter(obj, CreateGuid((string)o));
  289. }
  290. }
  291. }
  292. private long CreateLong(string s)
  293. {
  294. long num = 0L;
  295. bool neg = false;
  296. foreach (char cc in s)
  297. {
  298. switch (cc)
  299. {
  300. case '-':
  301. neg = true;
  302. break;
  303. case '+':
  304. neg = false;
  305. break;
  306. default:
  307. num *= 10;
  308. num += cc - 48;
  309. break;
  310. }
  311. }
  312. return neg ? (-num) : num;
  313. }
  314. private object CreateEnum(Type pt, string v)
  315. {
  316. return Enum.Parse(pt, v);
  317. }
  318. private Guid CreateGuid(string s)
  319. {
  320. if (s.Length > 30)
  321. {
  322. return new Guid(s);
  323. }
  324. return new Guid(Convert.FromBase64String(s));
  325. }
  326. private DateTime CreateDateTime(string value)
  327. {
  328. bool utc = false;
  329. int year = (int)CreateLong(value.Substring(0, 4));
  330. int month = (int)CreateLong(value.Substring(5, 2));
  331. int day = (int)CreateLong(value.Substring(8, 2));
  332. int hour = (int)CreateLong(value.Substring(11, 2));
  333. int min = (int)CreateLong(value.Substring(14, 2));
  334. int sec = (int)CreateLong(value.Substring(17, 2));
  335. if (value.EndsWith("Z"))
  336. {
  337. utc = true;
  338. }
  339. if (!_params.UseUTCDateTime && !utc)
  340. {
  341. return new DateTime(year, month, day, hour, min, sec);
  342. }
  343. return new DateTime(year, month, day, hour, min, sec, DateTimeKind.Utc).ToLocalTime();
  344. }
  345. private object CreateArray(ArrayList data, Type pt, Type bt, Dictionary<string, object> globalTypes)
  346. {
  347. ArrayList col = new ArrayList();
  348. foreach (object ob in data)
  349. {
  350. if (ob is IDictionary)
  351. {
  352. col.Add(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt, null));
  353. }
  354. else
  355. {
  356. col.Add(ChangeType(ob, bt));
  357. }
  358. }
  359. return col.ToArray(bt);
  360. }
  361. private object CreateGenericList(ArrayList data, Type pt, Type bt, Dictionary<string, object> globalTypes)
  362. {
  363. IList col = (IList)Reflection.Instance.FastCreateInstance(pt);
  364. foreach (object ob in data)
  365. {
  366. if (ob is IDictionary)
  367. {
  368. col.Add(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt, null));
  369. }
  370. else if (ob is ArrayList)
  371. {
  372. col.Add(((ArrayList)ob).ToArray());
  373. }
  374. else
  375. {
  376. col.Add(ChangeType(ob, bt));
  377. }
  378. }
  379. return col;
  380. }
  381. private object CreateStringKeyDictionary(Dictionary<string, object> reader, Type pt, Type[] types, Dictionary<string, object> globalTypes)
  382. {
  383. IDictionary col = (IDictionary)Reflection.Instance.FastCreateInstance(pt);
  384. Type t1 = null;
  385. Type t2 = null;
  386. if (types != null)
  387. {
  388. t1 = types[0];
  389. t2 = types[1];
  390. }
  391. foreach (KeyValuePair<string, object> values in reader)
  392. {
  393. string key = values.Key;
  394. object val = null;
  395. val = ((!(values.Value is Dictionary<string, object>)) ? ChangeType(values.Value, t2) : ParseDictionary((Dictionary<string, object>)values.Value, globalTypes, t2, null));
  396. col.Add(key, val);
  397. }
  398. return col;
  399. }
  400. private object CreateDictionary(ArrayList reader, Type pt, Type[] types, Dictionary<string, object> globalTypes)
  401. {
  402. IDictionary col = (IDictionary)Reflection.Instance.FastCreateInstance(pt);
  403. Type t1 = null;
  404. Type t2 = null;
  405. if (types != null)
  406. {
  407. t1 = types[0];
  408. t2 = types[1];
  409. }
  410. foreach (Dictionary<string, object> values in reader)
  411. {
  412. object key = values["k"];
  413. object val = values["v"];
  414. key = ((!(key is Dictionary<string, object>)) ? ChangeType(key, t1) : ParseDictionary((Dictionary<string, object>)key, globalTypes, t1, null));
  415. val = ((!(val is Dictionary<string, object>)) ? ChangeType(val, t2) : ParseDictionary((Dictionary<string, object>)val, globalTypes, t2, null));
  416. col.Add(key, val);
  417. }
  418. return col;
  419. }
  420. private Type GetChangeType(Type conversionType)
  421. {
  422. if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
  423. {
  424. return conversionType.GetGenericArguments()[0];
  425. }
  426. return conversionType;
  427. }
  428. private DataSet CreateDataset(Dictionary<string, object> reader, Dictionary<string, object> globalTypes)
  429. {
  430. DataSet ds = new DataSet();
  431. ds.EnforceConstraints = false;
  432. ds.BeginInit();
  433. ReadSchema(reader, ds, globalTypes);
  434. foreach (KeyValuePair<string, object> pair in reader)
  435. {
  436. if (!(pair.Key == "$type") && !(pair.Key == "$schema"))
  437. {
  438. ArrayList rows = (ArrayList)pair.Value;
  439. if (rows != null)
  440. {
  441. DataTable dt = ds.Tables[pair.Key];
  442. ReadDataTable(rows, dt);
  443. }
  444. }
  445. }
  446. ds.EndInit();
  447. return ds;
  448. }
  449. private void ReadSchema(Dictionary<string, object> reader, DataSet ds, Dictionary<string, object> globalTypes)
  450. {
  451. object schema = reader["$schema"];
  452. if (schema is string)
  453. {
  454. TextReader tr = new StringReader((string)schema);
  455. ds.ReadXmlSchema(tr);
  456. return;
  457. }
  458. DatasetSchema ms = (DatasetSchema)ParseDictionary((Dictionary<string, object>)schema, globalTypes, typeof(DatasetSchema), null);
  459. ds.DataSetName = ms.Name;
  460. for (int i = 0; i < ms.Info.Count; i += 3)
  461. {
  462. if (!ds.Tables.Contains(ms.Info[i]))
  463. {
  464. ds.Tables.Add(ms.Info[i]);
  465. }
  466. ds.Tables[ms.Info[i]].Columns.Add(ms.Info[i + 1], Type.GetType(ms.Info[i + 2]));
  467. }
  468. }
  469. private void ReadDataTable(ArrayList rows, DataTable dt)
  470. {
  471. dt.BeginInit();
  472. dt.BeginLoadData();
  473. List<int> guidcols = new List<int>();
  474. List<int> datecol = new List<int>();
  475. foreach (DataColumn c in dt.Columns)
  476. {
  477. if (c.DataType == typeof(Guid) || c.DataType == typeof(Guid?))
  478. {
  479. guidcols.Add(c.Ordinal);
  480. }
  481. if (_params.UseUTCDateTime && (c.DataType == typeof(DateTime) || c.DataType == typeof(DateTime?)))
  482. {
  483. datecol.Add(c.Ordinal);
  484. }
  485. }
  486. foreach (ArrayList row in rows)
  487. {
  488. object[] v = new object[row.Count];
  489. row.CopyTo(v, 0);
  490. foreach (int j in guidcols)
  491. {
  492. string s2 = (string)v[j];
  493. if (s2 != null && s2.Length < 36)
  494. {
  495. v[j] = new Guid(Convert.FromBase64String(s2));
  496. }
  497. }
  498. if (_params.UseUTCDateTime)
  499. {
  500. foreach (int i in datecol)
  501. {
  502. string s = (string)v[i];
  503. if (s != null)
  504. {
  505. v[i] = CreateDateTime(s);
  506. }
  507. }
  508. }
  509. dt.Rows.Add(v);
  510. }
  511. dt.EndLoadData();
  512. dt.EndInit();
  513. }
  514. private DataTable CreateDataTable(Dictionary<string, object> reader, Dictionary<string, object> globalTypes)
  515. {
  516. DataTable dt = new DataTable();
  517. object schema = reader["$schema"];
  518. if (schema is string)
  519. {
  520. TextReader tr = new StringReader((string)schema);
  521. dt.ReadXmlSchema(tr);
  522. }
  523. else
  524. {
  525. DatasetSchema ms = (DatasetSchema)ParseDictionary((Dictionary<string, object>)schema, globalTypes, typeof(DatasetSchema), null);
  526. dt.TableName = ms.Info[0];
  527. for (int i = 0; i < ms.Info.Count; i += 3)
  528. {
  529. dt.Columns.Add(ms.Info[i + 1], Type.GetType(ms.Info[i + 2]));
  530. }
  531. }
  532. foreach (KeyValuePair<string, object> pair in reader)
  533. {
  534. if (!(pair.Key == "$type") && !(pair.Key == "$schema"))
  535. {
  536. ArrayList rows = (ArrayList)pair.Value;
  537. if (rows != null && dt.TableName.Equals(pair.Key, StringComparison.InvariantCultureIgnoreCase))
  538. {
  539. ReadDataTable(rows, dt);
  540. }
  541. }
  542. }
  543. return dt;
  544. }
  545. }