JsonSerializer.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Jint.Native.Array;
  5. using Jint.Native.Global;
  6. using Jint.Native.Object;
  7. using Jint.Runtime;
  8. using Jint.Runtime.Descriptors;
  9. namespace Jint.Native.Json
  10. {
  11. public class JsonSerializer
  12. {
  13. private readonly Engine _engine;
  14. public JsonSerializer(Engine engine)
  15. {
  16. _engine = engine;
  17. }
  18. Stack<object> _stack;
  19. string _indent, _gap;
  20. List<string> _propertyList;
  21. object _replacerFunction = Undefined.Instance;
  22. public object Serialize(object value, object replacer, object space)
  23. {
  24. _stack = new Stack<object>();
  25. if (TypeConverter.GetType(replacer) == TypeCode.Object)
  26. {
  27. if (replacer is ICallable)
  28. {
  29. _replacerFunction = replacer;
  30. }
  31. else
  32. {
  33. var replacerObj = (ObjectInstance) replacer;
  34. if (replacerObj.Class == "Array")
  35. {
  36. _propertyList = new List<string>();
  37. }
  38. foreach (var property in replacerObj.Properties.Values)
  39. {
  40. object v = _engine.GetValue(property);
  41. string item = null;
  42. var type = TypeConverter.GetType(v);
  43. if (type == TypeCode.String)
  44. {
  45. item = (string)v;
  46. }
  47. else if (type == TypeCode.Double)
  48. {
  49. item = TypeConverter.ToString(v);
  50. }
  51. else if(type == TypeCode.Object)
  52. {
  53. var propertyObj = (ObjectInstance) v;
  54. if (propertyObj.Class == "String" || propertyObj.Class == "Number")
  55. {
  56. item = TypeConverter.ToString(propertyObj);
  57. }
  58. }
  59. if (item != null && !_propertyList.Contains(item))
  60. {
  61. _propertyList.Add(item);
  62. }
  63. }
  64. }
  65. }
  66. var spaceObj = space as ObjectInstance;
  67. if (spaceObj != null)
  68. {
  69. if (spaceObj.Class == "Number")
  70. {
  71. space = TypeConverter.ToNumber(spaceObj);
  72. }
  73. else if (spaceObj.Class == "String")
  74. {
  75. space = TypeConverter.ToString(spaceObj);
  76. }
  77. }
  78. // defining the gap
  79. if (TypeConverter.GetType(space) == TypeCode.Double)
  80. {
  81. _gap = new System.String(' ', (int) System.Math.Min(10, (double) space));
  82. }
  83. else if (TypeConverter.GetType(space) == TypeCode.String)
  84. {
  85. var stringSpace = (string) space;
  86. _gap = stringSpace.Length <= 10 ? stringSpace : stringSpace.Substring(0, 10);
  87. }
  88. else
  89. {
  90. _gap = "";
  91. }
  92. var wrapper = _engine.Object.Construct(Arguments.Empty);
  93. wrapper.DefineOwnProperty("",
  94. new DataDescriptor(value)
  95. {
  96. Configurable = true,
  97. Enumerable = true,
  98. Writable = true
  99. }, false);
  100. return Str("", wrapper);
  101. }
  102. private string Str(string key, ObjectInstance holder)
  103. {
  104. var value = holder.Get(key);
  105. var valueObj = value as ObjectInstance;
  106. if (valueObj != null)
  107. {
  108. var toJson = valueObj.Get("toJSON") as ICallable;
  109. if (toJson != null)
  110. {
  111. value = toJson.Call(value, Arguments.From(key));
  112. }
  113. }
  114. if (_replacerFunction != Undefined.Instance)
  115. {
  116. var replacerFunctionCallable = (ICallable)_replacerFunction;
  117. value = replacerFunctionCallable.Call(holder, Arguments.From(key));
  118. }
  119. valueObj = value as ObjectInstance;
  120. if (valueObj != null)
  121. {
  122. switch (valueObj.Class)
  123. {
  124. case "Number":
  125. value = TypeConverter.ToNumber(value);
  126. break;
  127. case "String":
  128. value = TypeConverter.ToString(value);
  129. break;
  130. case "Boolean":
  131. value = ((IPrimitiveType) value).PrimitiveValue;
  132. break;
  133. }
  134. }
  135. if (value == Null.Instance)
  136. {
  137. return "null";
  138. }
  139. if (true.Equals(value))
  140. {
  141. return "true";
  142. }
  143. if (false.Equals(value))
  144. {
  145. return "false";
  146. }
  147. if (TypeConverter.GetType(value) == TypeCode.String)
  148. {
  149. return Quote((string) value);
  150. }
  151. if (TypeConverter.GetType(value) == TypeCode.Double)
  152. {
  153. if (GlobalObject.IsFinite(this, Arguments.From(value)))
  154. {
  155. return TypeConverter.ToString(value);
  156. }
  157. return "null";
  158. }
  159. valueObj = value as ObjectInstance;
  160. var valueCallable = valueObj as ICallable;
  161. if (valueObj != null && valueCallable == null)
  162. {
  163. if (valueObj.Class == "Array")
  164. {
  165. return SerializeArray((ArrayInstance)value);
  166. }
  167. return SerializeObject(valueObj);
  168. }
  169. return "null";
  170. }
  171. private string Quote(string value)
  172. {
  173. var product = "\"";
  174. foreach (char c in value)
  175. {
  176. switch (c)
  177. {
  178. case '\"':
  179. product += "\\\"";
  180. break;
  181. case '\\':
  182. product += "\\\\";
  183. break;
  184. case '\b':
  185. product += "\\b";
  186. break;
  187. case '\f':
  188. product += "\\f";
  189. break;
  190. case '\n':
  191. product += "\\n";
  192. break;
  193. case '\r':
  194. product += "\\r";
  195. break;
  196. case '\t':
  197. product += "\\t";
  198. break;
  199. default:
  200. if (c < 0x20)
  201. {
  202. product += "\\u";
  203. product += ((int) c).ToString("x4");
  204. }
  205. else
  206. product += c;
  207. break;
  208. }
  209. }
  210. product += "\"";
  211. return product;
  212. }
  213. private string SerializeArray(ArrayInstance value)
  214. {
  215. EnsureNonCyclicity(value);
  216. _stack.Push(value);
  217. var stepback = _indent;
  218. _indent = _indent + _gap;
  219. var partial = new List<string>();
  220. var len = TypeConverter.ToUint32(value.Get("length"));
  221. for (int i = 0; i < len; i++)
  222. {
  223. var strP = Str(TypeConverter.ToString(i), value);
  224. partial.Add(strP);
  225. }
  226. if (partial.Count == 0)
  227. {
  228. return "[]";
  229. }
  230. var separator = ",";
  231. if (_gap != "")
  232. {
  233. separator += "\n" + _indent;
  234. }
  235. var properties = System.String.Join(separator, partial.ToArray());
  236. string final = "[" + properties + "]";
  237. _stack.Pop();
  238. _indent = stepback;
  239. return final;
  240. }
  241. private void EnsureNonCyclicity(object value)
  242. {
  243. if (value == null)
  244. {
  245. throw new ArgumentNullException("value");
  246. }
  247. if (_stack.Contains(value))
  248. {
  249. throw new JavaScriptException(_engine.TypeError, "Cyclic reference detected.");
  250. }
  251. }
  252. private string SerializeObject(ObjectInstance value)
  253. {
  254. string final;
  255. EnsureNonCyclicity(value);
  256. _stack.Push(value);
  257. var stepback = _indent;
  258. _indent += _gap;
  259. var k = _propertyList;
  260. if (k == null)
  261. {
  262. k = value.Properties.Where(x => x.Value.Enumerable).Select(x => x.Key).ToList();
  263. }
  264. var partial = new List<string>();
  265. foreach (var p in k)
  266. {
  267. var strP = Str(p, value);
  268. if (strP != "null")
  269. {
  270. var member = Quote(p) + ":";
  271. if (_gap != "")
  272. {
  273. member += " ";
  274. }
  275. member += strP;
  276. partial.Add(member);
  277. }
  278. }
  279. if (partial.Count == 0)
  280. {
  281. final = "{}";
  282. }
  283. else
  284. {
  285. var separator = ",";
  286. if (_gap != "")
  287. {
  288. separator += "\n" + _indent;
  289. }
  290. var properties = System.String.Join(separator, partial.ToArray());
  291. final = "{" + properties + "}";
  292. }
  293. _stack.Pop();
  294. _indent = stepback;
  295. return final;
  296. }
  297. }
  298. }