JsonSerializer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. JsValue _replacerFunction = Undefined.Instance;
  22. public JsValue Serialize(JsValue value, JsValue replacer, JsValue space)
  23. {
  24. _stack = new Stack<object>();
  25. // for JSON.stringify(), any function passed as the first argument will return undefined
  26. // if the replacer is not defined. The function is not called either.
  27. if (value.Is<ICallable>() && replacer == Undefined.Instance)
  28. {
  29. return Undefined.Instance;
  30. }
  31. if (replacer.IsObject())
  32. {
  33. if (replacer.Is<ICallable>())
  34. {
  35. _replacerFunction = replacer;
  36. }
  37. else
  38. {
  39. var replacerObj = replacer.AsObject();
  40. if (replacerObj.Class == "Array")
  41. {
  42. _propertyList = new List<string>();
  43. }
  44. foreach (var property in replacerObj.Properties.Values)
  45. {
  46. JsValue v = _engine.GetValue(property);
  47. string item = null;
  48. if (v.IsString())
  49. {
  50. item = v.AsString();
  51. }
  52. else if (v.IsNumber())
  53. {
  54. item = TypeConverter.ToString(v);
  55. }
  56. else if (v.IsObject())
  57. {
  58. var propertyObj = v.AsObject();
  59. if (propertyObj.Class == "String" || propertyObj.Class == "Number")
  60. {
  61. item = TypeConverter.ToString(v);
  62. }
  63. }
  64. if (item != null && !_propertyList.Contains(item))
  65. {
  66. _propertyList.Add(item);
  67. }
  68. }
  69. }
  70. }
  71. if (space.IsObject())
  72. {
  73. var spaceObj = space.AsObject();
  74. if (spaceObj.Class == "Number")
  75. {
  76. space = TypeConverter.ToNumber(spaceObj);
  77. }
  78. else if (spaceObj.Class == "String")
  79. {
  80. space = TypeConverter.ToString(spaceObj);
  81. }
  82. }
  83. // defining the gap
  84. if (space.IsNumber())
  85. {
  86. if (space.AsNumber() > 0) {
  87. _gap = new System.String(' ', (int)System.Math.Min(10, space.AsNumber()));
  88. }
  89. else
  90. {
  91. _gap = string.Empty;
  92. }
  93. }
  94. else if (space.IsString())
  95. {
  96. var stringSpace = space.AsString();
  97. _gap = stringSpace.Length <= 10 ? stringSpace : stringSpace.Substring(0, 10);
  98. }
  99. else
  100. {
  101. _gap = string.Empty;
  102. }
  103. var wrapper = _engine.Object.Construct(Arguments.Empty);
  104. wrapper.DefineOwnProperty("", new PropertyDescriptor(value, true, true, true), false);
  105. return Str("", wrapper);
  106. }
  107. private JsValue Str(string key, ObjectInstance holder)
  108. {
  109. var value = holder.Get(key);
  110. if (value.IsObject())
  111. {
  112. var toJson = value.AsObject().Get("toJSON");
  113. if (toJson.IsObject())
  114. {
  115. var callableToJson = toJson.AsObject() as ICallable;
  116. if (callableToJson != null)
  117. {
  118. value = callableToJson.Call(value, Arguments.From(key));
  119. }
  120. }
  121. }
  122. if (_replacerFunction != Undefined.Instance)
  123. {
  124. var replacerFunctionCallable = (ICallable)_replacerFunction.AsObject();
  125. value = replacerFunctionCallable.Call(holder, Arguments.From(key, value));
  126. }
  127. if (value.IsObject())
  128. {
  129. var valueObj = value.AsObject();
  130. switch (valueObj.Class)
  131. {
  132. case "Number":
  133. value = TypeConverter.ToNumber(value);
  134. break;
  135. case "String":
  136. value = TypeConverter.ToString(value);
  137. break;
  138. case "Boolean":
  139. value = TypeConverter.ToPrimitive(value);
  140. break;
  141. case "Array":
  142. value = SerializeArray(value.As<ArrayInstance>());
  143. return value;
  144. case "Object":
  145. value = SerializeObject(value.AsObject());
  146. return value;
  147. }
  148. }
  149. if (value == Null.Instance)
  150. {
  151. return "null";
  152. }
  153. if (value.IsBoolean() && value.AsBoolean())
  154. {
  155. return "true";
  156. }
  157. if (value.IsBoolean() && !value.AsBoolean())
  158. {
  159. return "false";
  160. }
  161. if (value.IsString())
  162. {
  163. return Quote(value.AsString());
  164. }
  165. if (value.IsNumber())
  166. {
  167. if (GlobalObject.IsFinite(Undefined.Instance, Arguments.From(value)).AsBoolean())
  168. {
  169. return TypeConverter.ToString(value);
  170. }
  171. return "null";
  172. }
  173. var isCallable = value.IsObject() && value.AsObject() is ICallable;
  174. if (value.IsObject() && isCallable == false)
  175. {
  176. if (value.AsObject().Class == "Array")
  177. {
  178. return SerializeArray(value.As<ArrayInstance>());
  179. }
  180. return SerializeObject(value.AsObject());
  181. }
  182. return JsValue.Undefined;
  183. }
  184. private string Quote(string value)
  185. {
  186. var product = "\"";
  187. foreach (char c in value)
  188. {
  189. switch (c)
  190. {
  191. case '\"':
  192. product += "\\\"";
  193. break;
  194. case '\\':
  195. product += "\\\\";
  196. break;
  197. case '\b':
  198. product += "\\b";
  199. break;
  200. case '\f':
  201. product += "\\f";
  202. break;
  203. case '\n':
  204. product += "\\n";
  205. break;
  206. case '\r':
  207. product += "\\r";
  208. break;
  209. case '\t':
  210. product += "\\t";
  211. break;
  212. default:
  213. if (c < 0x20)
  214. {
  215. product += "\\u";
  216. product += ((int) c).ToString("x4");
  217. }
  218. else
  219. product += c;
  220. break;
  221. }
  222. }
  223. product += "\"";
  224. return product;
  225. }
  226. private string SerializeArray(ArrayInstance value)
  227. {
  228. EnsureNonCyclicity(value);
  229. _stack.Push(value);
  230. var stepback = _indent;
  231. _indent = _indent + _gap;
  232. var partial = new List<string>();
  233. var len = TypeConverter.ToUint32(value.Get("length"));
  234. for (int i = 0; i < len; i++)
  235. {
  236. var strP = Str(TypeConverter.ToString(i), value);
  237. if (strP == JsValue.Undefined)
  238. strP = "null";
  239. partial.Add(strP.AsString());
  240. }
  241. if (partial.Count == 0)
  242. {
  243. return "[]";
  244. }
  245. string final;
  246. if (_gap == "")
  247. {
  248. var separator = ",";
  249. var properties = System.String.Join(separator, partial.ToArray());
  250. final = "[" + properties + "]";
  251. }
  252. else
  253. {
  254. var separator = ",\n" + _indent;
  255. var properties = System.String.Join(separator, partial.ToArray());
  256. final = "[\n" + _indent + properties + "\n" + stepback + "]";
  257. }
  258. _stack.Pop();
  259. _indent = stepback;
  260. return final;
  261. }
  262. private void EnsureNonCyclicity(object value)
  263. {
  264. if (value == null)
  265. {
  266. throw new ArgumentNullException("value");
  267. }
  268. if (_stack.Contains(value))
  269. {
  270. throw new JavaScriptException(_engine.TypeError, "Cyclic reference detected.");
  271. }
  272. }
  273. private string SerializeObject(ObjectInstance value)
  274. {
  275. string final;
  276. EnsureNonCyclicity(value);
  277. _stack.Push(value);
  278. var stepback = _indent;
  279. _indent += _gap;
  280. var k = _propertyList;
  281. if (k == null)
  282. {
  283. k = value.Properties.Where(x => x.Value.Enumerable.Value.AsBoolean()).Select(x => x.Key).ToList();
  284. }
  285. var partial = new List<string>();
  286. foreach (var p in k)
  287. {
  288. var strP = Str(p, value);
  289. if (strP != JsValue.Undefined)
  290. {
  291. var member = Quote(p) + ":";
  292. if (_gap != "")
  293. {
  294. member += " ";
  295. }
  296. member += strP.AsString(); // TODO:This could be undefined
  297. partial.Add(member);
  298. }
  299. }
  300. if (partial.Count == 0)
  301. {
  302. final = "{}";
  303. }
  304. else
  305. {
  306. if (_gap == "")
  307. {
  308. var separator = ",";
  309. var properties = System.String.Join(separator, partial.ToArray());
  310. final = "{" + properties + "}";
  311. }
  312. else
  313. {
  314. var separator = ",\n" + _indent;
  315. var properties = System.String.Join(separator, partial.ToArray());
  316. final = "{\n" + _indent + properties + "\n" + stepback + "}";
  317. }
  318. }
  319. _stack.Pop();
  320. _indent = stepback;
  321. return final;
  322. }
  323. }
  324. }