You are hereBlogs / rahul's blog / Custom JSON Serialization of objects using ExtJs

Custom JSON Serialization of objects using ExtJs


rahul's picture

By rahul - Posted on 04 February 2010

I thought this should be pretty easy to accomplish, with the extensive feature set that ExtJs provides. What I basically wanted to control was how the objects of my class are serialized by the Ext.util.JSON.encode (Ext.encode) method (I needed this for serialization of enums I discussed in the pevious blog posts, here and here).

A quick Google search threw this forum entry on top. The approach suggested by condor (ExtJs Team Member) was compelling, and I immediately copied over the code. And I immediately hit another road block (that I am discussing here).

The problem is the following code:

var encode = Ext.encode;
Ext.encode = Ext.util.JSON.encode = function(o){
if(o && typeof o.toJSON == 'function'){
return o.toJSON();
}
return encode(o);
};

suggested by condor works only for the top-level object on which Ext.encode is called directly. That object can have custom serialization via the toJSON method suggested. However, the direct and descendent properties of the top-level object did not receive this feature, because they are serialized by the private doEncode method of the JSON utility class. As as the method is private, there is no easy intuitive way to override the serialization process.

I was pretty disappointed at this, considering the extensibility of the ExtJs frameowork. So, finally I had to deploy a work-around of my own.

I had to add the following 2 lines to the JSON class (beginning at line 47):

} else if (o && typeof o.toJSON == 'function') {
return o.toJSON();

I was using ExtJs 3.1 at the time I wrote this blog post. Instead of hacking into the core, I just copy-pasted the class, and added these lines.

Hope this helps someone in the near future. Moving forward, I would expect ExtJs to incorporate such extensibility into the core itself for custom JSON serialization.

Post new comment

The content of this field is kept private and will not be shown publicly.

Mollom CAPTCHA (play audio CAPTCHA)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.