/** * @class Ext.data.JsonReader * @extends Ext.data.DataReader *

Data reader class to create an Array of {@link Ext.data.Record} objects from a JSON response * based on mappings in a provided {@link Ext.data.Record} constructor.

*

Example code:

*

var Employee = Ext.data.Record.create([
    {name: 'firstname'},                  // map the Record's "firstname" field to the row object's key of the same name
    {name: 'job', mapping: 'occupation'}  // map the Record's "job" field to the row object's "occupation" key
]);
var myReader = new Ext.data.JsonReader(
    {                             // The metadata property, with configuration options:
        totalProperty: "results", //   the property which contains the total dataset size (optional)
        root: "rows",             //   the property which contains an Array of record data objects
        idProperty: "id"          //   the property within each row object that provides an ID for the record (optional)
    },
    Employee  // {@link Ext.data.Record} constructor that provides mapping for JSON object
);
*

This would consume a JSON data object of the form:


{
    results: 2,  // Reader's configured totalProperty
    rows: [      // Reader's configured root
        { id: 1, firstname: 'Bill', occupation: 'Gardener' },         // a row object
        { id: 2, firstname: 'Ben' , occupation: 'Horticulturalist' }  // another row object
    ]
}
*

Automatic configuration using metaData

*

It is possible to change a JsonReader's metadata at any time by including a metaData * property in the JSON data object. If the JSON data object has a metaData property, a * {@link Ext.data.Store Store} object using this Reader will reconfigure itself to use the newly provided * field definition and fire its {@link Ext.data.Store#metachange metachange} event. The metachange event * handler may interrogate the metaData property to perform any configuration required. * Note that reconfiguring a Store potentially invalidates objects which may refer to Fields or Records * which no longer exist.

*

The metaData property in the JSON data object may contain:

*
*

To use this facility to send the same data as the example above (without having to code the creation * of the Record constructor), you would create the JsonReader like this:


var myReader = new Ext.data.JsonReader();
*

The first data packet from the server would configure the reader by containing a * metaData property and the data. For example, the JSON data object might take * the form:


{
    metaData: {
        idProperty: 'id',
        root: 'rows',
        totalProperty: 'results',
        fields: [
            {name: 'name'},
            {name: 'job', mapping: 'occupation'}
        ],
        sortInfo: {field: 'name', direction:'ASC'}, // used by store to set its sortInfo
        foo: 'bar' // custom property
    },
    results: 2,
    rows: [ // an Array
        { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
        { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' }
    ]
}
* @cfg {String} totalProperty [total] Name of the property from which to retrieve the total number of records * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being * paged from the remote server. Defaults to total. * @cfg {String} successProperty [success] Name of the property from which to * retrieve the success attribute. Defaults to success. See * {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception} * for additional information. * @cfg {String} root [undefined] Required. The name of the property * which contains the Array of row objects. Defaults to undefined. * An exception will be thrown if the root property is undefined. The data packet * value for this property should be an empty array to clear the data or show * no data. * @cfg {String} idProperty [id] Name of the property within a row object that contains a record identifier value. Defaults to id * @constructor * Create a new JsonReader * @param {Object} meta Metadata configuration options. * @param {Array/Object} recordType *

Either an Array of {@link Ext.data.Field Field} definition objects (which * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record} * constructor created from {@link Ext.data.Record#create}.

*/ Ext.data.JsonReader = function(meta, recordType){ meta = meta || {}; // default idProperty, successProperty & totalProperty -> "id", "success", "total" Ext.applyIf(meta, { idProperty: 'id', successProperty: 'success', totalProperty: 'total' }); Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields); }; Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, { /** * This JsonReader's metadata as passed to the constructor, or as passed in * the last data packet's metaData property. * @type Mixed * @property meta */ /** * This method is only used by a DataProxy which has retrieved data from a remote server. * @param {Object} response The XHR object which contains the JSON data in its responseText. * @return {Object} data A data block which is used by an Ext.data.Store object as * a cache of Ext.data.Records. */ read : function(response){ var json = response.responseText; var o = Ext.decode(json); if(!o) { throw {message: "JsonReader.read: Json object not found"}; } return this.readRecords(o); }, // private function a store will implement onMetaChange : function(meta, recordType, o){ }, /** * @ignore */ simpleAccess: function(obj, subsc) { return obj[subsc]; }, /** * @ignore */ getJsonAccessor: function(){ var re = /[\[\.]/; return function(expr) { try { return(re.test(expr)) ? new Function("obj", "return obj." + expr) : function(obj){ return obj[expr]; }; } catch(e){} return Ext.emptyFn; }; }(), /** * Create a data block containing Ext.data.Records from a JSON object. * @param {Object} o An object which contains an Array of row objects in the property specified * in the config as 'root, and optionally a property, specified in the config as 'totalProperty' * which contains the total size of the dataset. * @return {Object} data A data block which is used by an Ext.data.Store object as * a cache of Ext.data.Records. */ readRecords : function(o){ /** * After any data loads, the raw JSON data is available for further custom processing. If no data is * loaded or there is a load exception this property will be undefined. * @type Object */ this.jsonData = o; if(o.metaData){ delete this.ef; this.meta = o.metaData; this.recordType = Ext.data.Record.create(o.metaData.fields); this.onMetaChange(this.meta, this.recordType, o); } var s = this.meta, Record = this.recordType, f = Record.prototype.fields, fi = f.items, fl = f.length, v; var root = this.getRoot(o), c = root.length, totalRecords = c, success = true; if(s.totalProperty){ v = parseInt(this.getTotal(o), 10); if(!isNaN(v)){ totalRecords = v; } } if(s.successProperty){ v = this.getSuccess(o); if(v === false || v === 'false'){ success = false; } } var records = []; for(var i = 0; i < c; i++){ var n = root[i]; var record = new Record(this.extractValues(n, fi, fl), this.getId(n)); record.json = n; records[i] = record; } return { success : success, records : records, totalRecords : totalRecords }; }, // private buildExtractors : function() { if(this.ef){ return; } var s = this.meta, Record = this.recordType, f = Record.prototype.fields, fi = f.items, fl = f.length; if(s.totalProperty) { this.getTotal = this.getJsonAccessor(s.totalProperty); } if(s.successProperty) { this.getSuccess = this.getJsonAccessor(s.successProperty); } this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;}; if (s.id || s.idProperty) { var g = this.getJsonAccessor(s.id || s.idProperty); this.getId = function(rec) { var r = g(rec); return (r === undefined || r === "") ? null : r; }; } else { this.getId = function(){return null;}; } var ef = []; for(var i = 0; i < fl; i++){ f = fi[i]; var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name; ef.push(this.getJsonAccessor(map)); } this.ef = ef; }, // private extractValues extractValues: function(data, items, len) { var f, values = {}; for(var j = 0; j < len; j++){ f = items[j]; var v = this.ef[j](data); values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data); } return values; }, /** * Decode a json response from server. * @param {String} action [Ext.data.Api.actions.create|read|update|destroy] * @param {Object} response */ readResponse : function(action, response) { var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response; if(!o) { throw new Ext.data.JsonReader.Error('response'); } if (Ext.isEmpty(o[this.meta.successProperty])) { throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty); } // TODO, separate empty and undefined exceptions. if (action === Ext.data.Api.actions.create) { if (Ext.isEmpty(o[this.meta.root])) { throw new Ext.data.JsonReader.Error('root-emtpy', this.meta.root); } else if (o[this.meta.root] === undefined) { throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root); } } return o; } }); /** * @class Ext.data.JsonReader.Error * Error class for JsonReader */ Ext.data.JsonReader.Error = Ext.extend(Ext.Error, { constructor : function(message, arg) { this.arg = arg; Ext.Error.call(this, message); }, name : 'Ext.data.JsonReader' }); Ext.apply(Ext.data.JsonReader.Error.prototype, { lang: { 'response': "An error occurred while json-decoding your server response", 'successProperty-response': 'Could not locate your "successProperty" in your server response. Please review your JsonReader config to ensure the config-property "successProperty" matches the property in your server-response. See the JsonReader docs.', 'root-undefined-response': 'Could not locate your "root" property in your server response. Please review your JsonReader config to ensure the config-property "root" matches the property your server-response. See the JsonReader docs.', 'root-undefined-config': 'Your JsonReader was configured without a "root" property. Please review your JsonReader config and make sure to define the root property. See the JsonReader docs.', 'idProperty-undefined' : 'Your JsonReader was configured without an "idProperty" Please review your JsonReader configuration and ensure the "idProperty" is set (e.g.: "id"). See the JsonReader docs.', 'root-emtpy': 'Data was expected to be returned by the server in the "root" property of the response. Please review your JsonReader configuration to ensure the "root" property matches that returned in the server-response. See JsonReader docs.' } });