(function (self, toString) {
/**
* JSON.serialize & JSON.unserialize
* PHP __sleep, __wakeup, and Serializable interface concept for JSON protocol
* @author Andrea Giammarchi
* @license Mit Style License
* @version 0.0.1 a(bsolute)lpha
*/
if (typeof JSON.serialize !== "undefined") {
return;
}
function anonymous() {}
function parse(value) {
if (_info.hasOwnProperty(value)) {
return _info[value];
}
for (var
prototype = self,
path = value.split("."),
i = 0, length = path.length;
i < length; ++i
) {
prototype = prototype[path[i]];
}
if (typeof prototype === _function) {
prototype = prototype.prototype;
}
return (_info[value] = {
prototype: prototype,
unserialize: prototype.unserialize,
_wakeup: prototype._wakeup
});
}
function serialize(value) {
if (typeof value === "object" && value !== null) {
var object;
switch (toString.call(value)) {
case _Array:
object = [];
for (var i = value.length; i--;) {
object[i] = serialize(value[i]);
}
value = object;
break;
case _Object:
if (typeof value.serialize === _function) {
wakeup(value, object = JSON.parse(value.serialize()));
} else {
object = {};
if (typeof value._sleep === _function) {
for (var
keys = value._sleep(),
i = keys.length,
key;
i--;
) {
object[key = keys[i]] = value[key];
}
wakeup(value, object);
value = object;
} else {
wakeup(value, object);
}
for (var key in value) {
if (value.hasOwnProperty(key)) {
object[key] = serialize(value[key]);
}
}
}
value = object;
break;
}
}
return value;
}
function unserialize(value) {
if (typeof value === "object" && value !== null) {
switch (toString.call(value)) {
case _Array:
for (var i = value.length; i--;) {
value[i] = unserialize(value[i]);
}
break;
case _Object:
if (value.hasOwnProperty("_wakeup")) {
var object = parse(value._wakeup), key, instance;
anonymous.prototype = object.prototype;
instance = new anonymous();
if (typeof object.unserialize === _function) {
object.unserialize.call(instance, JSON.stringify(value));
} else {
for (key in value) {
if (value.hasOwnProperty(key) && key !== "_wakeup") {
instance[key] = unserialize(value[key]);
}
}
if (typeof object._wakeup === _function) {
object._wakeup.call(instance);
}
}
value = instance;
} else {
for (var key in value) {
if (value.hasOwnProperty(key)) {
value[key] = unserialize(value[key]);
}
}
}
break;
}
}
return value;
}
function wakeup(value, object) {
if (typeof value.serializer === "string") {
object._wakeup = value.serializer;
}
}
var
_function = typeof anonymous,
_info = {},
_Array = "[object Array]",
_Object = "[object Object]"
;
JSON.serialize = function (value, replacer, space) {
arguments[0] = serialize(value);
return JSON.stringify.apply(JSON, arguments);
};
JSON.unserialize = function (value, reviver) {
value = unserialize(JSON.parse.apply(JSON, arguments));
anonymous.prototype = _info = {};
return value;
};
}(this, Object.prototype.toString));