JsonInstance.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using Jint.Native.Object;
  2. using Jint.Runtime;
  3. using Jint.Runtime.Interop;
  4. namespace Jint.Native.Json
  5. {
  6. public sealed class JsonInstance : ObjectInstance
  7. {
  8. private readonly Engine _engine;
  9. private JsonInstance(Engine engine)
  10. : base(engine)
  11. {
  12. _engine = engine;
  13. Extensible = true;
  14. }
  15. public override string Class
  16. {
  17. get
  18. {
  19. return "JSON";
  20. }
  21. }
  22. public static JsonInstance CreateJsonObject(Engine engine)
  23. {
  24. var json = new JsonInstance(engine);
  25. json.Prototype = engine.Object.PrototypeObject;
  26. return json;
  27. }
  28. public void Configure()
  29. {
  30. FastAddProperty("parse", new ClrFunctionInstance(Engine, Parse, 2), true, false, true);
  31. FastAddProperty("stringify", new ClrFunctionInstance(Engine, Stringify, 3), true, false, true);
  32. }
  33. public JsValue Parse(JsValue thisObject, JsValue[] arguments)
  34. {
  35. var parser = new JsonParser(_engine);
  36. return parser.Parse(TypeConverter.ToString(arguments[0]));
  37. }
  38. public JsValue Stringify(JsValue thisObject, JsValue[] arguments)
  39. {
  40. JsValue
  41. value = Undefined.Instance,
  42. replacer = Undefined.Instance,
  43. space = Undefined.Instance;
  44. if (arguments.Length > 2)
  45. {
  46. space = arguments[2];
  47. }
  48. if (arguments.Length > 1)
  49. {
  50. replacer = arguments[1];
  51. }
  52. if (arguments.Length > 0)
  53. {
  54. value = arguments[0];
  55. }
  56. var serializer = new JsonSerializer(_engine);
  57. if (value == Undefined.Instance && replacer == Undefined.Instance) {
  58. return Undefined.Instance;
  59. }
  60. else {
  61. return serializer.Serialize(value, replacer, space);
  62. }
  63. }
  64. }
  65. }