Saturday 8 June 2013

How to specify optional or dynamic root element in JSON reader

Problem:
In Ext JS4, proxy reader will allow to specify root element property for your response (JSON, XML etc) in order to parse the response data. There will be a situation, where your response data doesn't contain root element (or) the root element will vary for each request of same model/store.

Solution:
We can achieve this by specifying a custom property in model/store proxy config and handle this property by overriding Ext.data.reader.Json class.


In your Model Class proxy config, there is a custom property optionalRoot with element name data.
proxy:{
type: 'json',
root: 'data',
optionalRoot: 'data' //custom property
...
..
}


In override js ,
Ext.override( Ext.data.reader.Json, {

readRecords: function(data) {
  // if the root element "data" not present in response, then take the whole response as root. For this set root as "".

  if(this.optionalRoot){
     if(this.root != "" && data[this.optionalRoot] == undefined ){
       this.root ="";
       this.buildExtractors();
     }else{
       this.root = this.optionalRoot;
       this.buildExtractors();
     }
  }
  var me = this,
//this has to be before the call to super because we use the meta data in the superclass readRecords

    if (me.getMeta) {
        meta = me.getMeta(data);
        if (meta) {
            me.onMetaChange(meta);
        }

    } else if (data.metaData) {
        me.onMetaChange(data.metaData);

    }

       /**
        * @property {Object} jsonData
        * A copy of this.rawData.
        * @deprecated Will be removed in Ext JS 5.0. This is just a copy of this.rawData - use that instead.
        */

       me.jsonData = data;

       return me.callParent([data]);

   }

});



Hope, you enjoyed this Post.

2 comments:

  1. Refer to this Suresh...i think you will appreciate this http://www.sencha.com/forum/showthread.php?196493-How-to-make-rootproperty-dynamic&p=785161#post785161

    ReplyDelete
  2. Hi,

    Thanks for contacting me. Yes, you are right. We can use setRootProperty() for dynamic rootproperty.

    Thanks,
    Suresh Ariya

    ReplyDelete