In general, there's no way (in a browser) so serialize objects with functions attached to them, since every function has a reference to it's outer scope. If the function references any of those variables, they won't exist anymore when you deserialize it.
What I would to is use the built-in (or json2.js) JSON.stringify
and JSON.parse
functions with the replacer
and reviver
parameters. Here's a partial example of how it would work:
JSON.stringify(yourObject, function(name, value) {
if (value instanceof LatLng) { // Could also check the name if you want
return 'LatLng(' + value.lat() + ',' + value.lng() + ')';
}
else if (...) {
// Some other type that needs custom serialization
}
else {
return value;
}
});
JSON.parse(jsonString, function(name, value) {
if (/^LatLng\(/.test(value)) { // Checking the name would be safer
var match = /LatLng\(([^,]+),([^,]+)\)/.exec(value);
return new LatLng(match[1], match[2]);
}
else if (...) {
...
}
else {
return value;
}
});
You can use any serialization format you want in your custom types. The "LatLng(latitude,longitude)" format is just one way of doing it. You could even return a javascript object that can be serialized to JSON natively.