| 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 |
|
| 16 |
/** |
| 17 |
* @fileoverview Defines a class for parsing JSON using the browser's built in |
| 18 |
* JSON library. |
| 19 |
*/ |
| 20 |
|
| 21 |
goog.provide('goog.json.NativeJsonProcessor'); |
| 22 |
|
| 23 |
goog.require('goog.asserts'); |
| 24 |
goog.require('goog.json.Processor'); |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
/** |
| 29 |
* A class that parses and stringifies JSON using the browser's built-in JSON |
| 30 |
* library, if it is available. |
| 31 |
* |
| 32 |
* Note that the native JSON api has subtle differences across browsers, so |
| 33 |
* use this implementation with care. See json_test#assertSerialize |
| 34 |
* for details on the differences from goog.json. |
| 35 |
* |
| 36 |
* This implementation is signficantly faster than goog.json, at least on |
| 37 |
* Chrome. See json_perf.html for a perf test showing the difference. |
| 38 |
* |
| 39 |
* @param {?goog.json.Replacer=} opt_replacer An optional replacer to use during |
| 40 |
* serialization. |
| 41 |
* @param {?goog.json.Reviver=} opt_reviver An optional reviver to use during |
| 42 |
* parsing. |
| 43 |
* @constructor |
| 44 |
* @implements {goog.json.Processor} |
| 45 |
* @final |
| 46 |
*/ |
| 47 |
goog.json.NativeJsonProcessor = function(opt_replacer, opt_reviver) { |
| 48 |
goog.asserts.assert(goog.isDef(goog.global['JSON']), 'JSON not defined'); |
| 49 |
|
| 50 |
/** |
| 51 |
* @type {goog.json.Replacer|null|undefined} |
| 52 |
* @private |
| 53 |
*/ |
| 54 |
this.replacer_ = opt_replacer; |
| 55 |
|
| 56 |
/** |
| 57 |
* @type {goog.json.Reviver|null|undefined} |
| 58 |
* @private |
| 59 |
*/ |
| 60 |
this.reviver_ = opt_reviver; |
| 61 |
}; |
| 62 |
|
| 63 |
|
| 64 |
/** @override */ |
| 65 |
goog.json.NativeJsonProcessor.prototype.stringify = function(object) { |
| 66 |
return goog.global['JSON'].stringify(object, this.replacer_); |
| 67 |
}; |
| 68 |
|
| 69 |
|
| 70 |
/** @override */ |
| 71 |
goog.json.NativeJsonProcessor.prototype.parse = function(s) { |
| 72 |
return goog.global['JSON'].parse(s, this.reviver_); |
| 73 |
}; |