Serialize object instances in Mojo WebOS

Mojo, the javascript framework in HP WebOS offer convenient ways to save data like Mojo.Model.Cookie…

Cookies can save javascript objects. Unfortunately, as this API is based on a JSON serialization, it can’t naturally deserialize all objects.
JSON can only serialize numbers, strings, booleans, arrays and objects. But when it serialize objects, obviously, only the object properties that can be serialized are serialized. Functions and prototype are not saved, and as a consequence not restored… In fact, arrays are the only objects that truly can be serialized…

For example, we can’t save Date instances… In fact, by default Date instance are serialized into ISO 8601 strings…

Mojo is based on the prototype javascript framework. To serialize an object in JSON, we just call the Object.toJSON function. When we look at the source code, we can see that this function call, if exists, a _toJSON method of the current serialized object (toJSON without underscore, in the real prototype framework, with underscore in Mojo). So if we implement a Date#toJSON method, we can change the way Date are serialized…

We can implement something like this :

This will broke the JSON specification, but if the string is deserialized in javascript with an eval(), this will create a new Date instance with the right parameters… But, prototype offer a String#evalJSON method. This method check the validity of the JSON string before evaluating it. The check is done with the String#isJSON method. And this method will broke on serialized date… We must update it to allow our new way to serialize dates…

So now, we can serialize date objects :

And the deserialization is automagically done with a :

That’s it… And this can be done with any objects…
Of course, this can also be done in non Mojo javascript environment…

Laisser un commentaire

Votre adresse ne sera pas publiée.

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.