YUI 3.x Home -

YUI Library Examples: JSON Utility: Rebuilding class instances from JSON data

Note: This is YUI 3.x. Looking for YUI 2.x?

JSON Utility: Rebuilding class instances from JSON data

This example illustrates one method of serializing and recreating class instances by using the replacer and reviver parameters to JSON.stringify and JSON.parse respectively.

(stringify results here)

The CaveMan class

For this example, we'll use a class CaveMan, with a property discovered that holds a Date instance, and a method getName.

Add freeze and thaw static methods

We'll add the methods responsible for serializing and reconstituting instances to the CaveMan class as static methods.

Reference the methods in replacer and reviver functions

We'll create an example namespace to hold our moving parts. In it, we'll add a method to pass to JSON.stringify that calls our custom serializer, and another method to pass to JSON.parse that detects the serialized structure and calls our thawing method.

The data to be serialized

We'll create a CaveMan instance and nest it in another object structure to illustrate how the thawing process still operates normally for all other data.

Thawing from the inside out and the Date instance

The reviver function passed to JSON.parse is applied to all key:value pairs in the raw parsed object from the deepest keys to the highest level. In our case, this means that the name and discovered properties will be passed through the reviver, and then the object containing those keys will be passed through.

We'll take advantage of this by watching for UTC formatted date strings (the default JSON serialization for Dates) and reviving them into proper Date instances before the containing object gets its turn in the reviver.

Now when the reviver function is evaluating the object it determines to be a CaveMan, the discovered property is correctly containing a Date instance.

Choose your serialization

You'll note there are two freeze and thaw operations going on in this example. One for our CaveMan class and one for Date instances. Their respective serialization and recreation techniques are very different. You are free to decide the serialized format of your objects. Choose whatever makes sense for your application.

Note: There is no explicit Date serialization method listed inline because JSON natively supports Date serialization. However, it is outside the scope of the parser's duty to create Date instances, so it's up to you to recreate them in the parse phase. Feel free to use the method included here.

Show and Tell

Now we add the event handlers to the example buttons to call JSON.stringify and parse with our example.cryo and example.revive methods, respectively.

Full Code Listing

Copyright © 2008 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings