nativejsonprocessor.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2012 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Defines a class for parsing JSON using the browser's built in
  16. * JSON library.
  17. */
  18. goog.provide('goog.json.NativeJsonProcessor');
  19. goog.require('goog.asserts');
  20. goog.require('goog.json.Processor');
  21. /**
  22. * A class that parses and stringifies JSON using the browser's built-in JSON
  23. * library, if it is available.
  24. *
  25. * Note that the native JSON api has subtle differences across browsers, so
  26. * use this implementation with care. See json_test#assertSerialize
  27. * for details on the differences from goog.json.
  28. *
  29. * This implementation is signficantly faster than goog.json, at least on
  30. * Chrome. See json_perf.html for a perf test showing the difference.
  31. *
  32. * @param {?goog.json.Replacer=} opt_replacer An optional replacer to use during
  33. * serialization.
  34. * @param {?goog.json.Reviver=} opt_reviver An optional reviver to use during
  35. * parsing.
  36. * @constructor
  37. * @implements {goog.json.Processor}
  38. * @final
  39. */
  40. goog.json.NativeJsonProcessor = function(opt_replacer, opt_reviver) {
  41. goog.asserts.assert(goog.isDef(goog.global['JSON']), 'JSON not defined');
  42. /**
  43. * @type {goog.json.Replacer|null|undefined}
  44. * @private
  45. */
  46. this.replacer_ = opt_replacer;
  47. /**
  48. * @type {goog.json.Reviver|null|undefined}
  49. * @private
  50. */
  51. this.reviver_ = opt_reviver;
  52. };
  53. /** @override */
  54. goog.json.NativeJsonProcessor.prototype.stringify = function(object) {
  55. return goog.global['JSON'].stringify(object, this.replacer_);
  56. };
  57. /** @override */
  58. goog.json.NativeJsonProcessor.prototype.parse = function(s) {
  59. return goog.global['JSON'].parse(s, this.reviver_);
  60. };