3 * Copyright(c) 2006-2010 Sencha Inc.
5 * http://www.sencha.com/license
8 * @class Ext.data.JsonReader
9 * @extends Ext.data.DataReader
10 * <p>Data reader class to create an Array of {@link Ext.data.Record} objects
11 * from a JSON packet based on mappings in a provided {@link Ext.data.Record}
13 * <p>Example code:</p>
15 var myReader = new Ext.data.JsonReader({
16 // metadata configuration options:
17 {@link #idProperty}: 'id'
18 {@link #root}: 'rows',
19 {@link #totalProperty}: 'results',
20 {@link Ext.data.DataReader#messageProperty}: "msg" // The element within the response that provides a user-feedback message (optional)
22 // the fields config option will internally create an {@link Ext.data.Record}
23 // constructor that provides mapping for reading the record data objects
24 {@link Ext.data.DataReader#fields fields}: [
25 // map Record's 'firstname' field to data object's key of same name
26 {name: 'name', mapping: 'firstname'},
27 // map Record's 'job' field to data object's 'occupation' key
28 {name: 'job', mapping: 'occupation'}
32 * <p>This would consume a JSON data object of the form:</p><pre><code>
34 results: 2000, // Reader's configured {@link #totalProperty}
35 rows: [ // Reader's configured {@link #root}
36 // record data objects:
37 { {@link #idProperty id}: 1, firstname: 'Bill', occupation: 'Gardener' },
38 { {@link #idProperty id}: 2, firstname: 'Ben' , occupation: 'Horticulturalist' },
43 * <p><b><u>Automatic configuration using metaData</u></b></p>
44 * <p>It is possible to change a JsonReader's metadata at any time by including
45 * a <b><tt>metaData</tt></b> property in the JSON data object. If the JSON data
46 * object has a <b><tt>metaData</tt></b> property, a {@link Ext.data.Store Store}
47 * object using this Reader will reconfigure itself to use the newly provided
48 * field definition and fire its {@link Ext.data.Store#metachange metachange}
49 * event. The metachange event handler may interrogate the <b><tt>metaData</tt></b>
50 * property to perform any configuration required.</p>
51 * <p>Note that reconfiguring a Store potentially invalidates objects which may
52 * refer to Fields or Records which no longer exist.</p>
53 * <p>To use this facility you would create the JsonReader like this:</p><pre><code>
54 var myReader = new Ext.data.JsonReader();
56 * <p>The first data packet from the server would configure the reader by
57 * containing a <b><tt>metaData</tt></b> property <b>and</b> the data. For
58 * example, the JSON data object might take the form:</p><pre><code>
61 "{@link #idProperty}": "id",
62 "{@link #root}": "rows",
63 "{@link #totalProperty}": "results"
64 "{@link #successProperty}": "success",
65 "{@link Ext.data.DataReader#fields fields}": [
67 {"name": "job", "mapping": "occupation"}
69 // used by store to set its sortInfo
74 // {@link Ext.PagingToolbar paging data} (if applicable)
80 // Reader's configured {@link #successProperty}
82 // Reader's configured {@link #totalProperty}
84 // Reader's configured {@link #root}
85 // (this data simulates 2 results {@link Ext.PagingToolbar per page})
86 "rows": [ // <b>*Note:</b> this must be an Array
87 { "id": 1, "name": "Bill", "occupation": "Gardener" },
88 { "id": 2, "name": "Ben", "occupation": "Horticulturalist" }
92 * <p>The <b><tt>metaData</tt></b> property in the JSON data object should contain:</p>
93 * <div class="mdetail-params"><ul>
94 * <li>any of the configuration options for this class</li>
95 * <li>a <b><tt>{@link Ext.data.Record#fields fields}</tt></b> property which
96 * the JsonReader will use as an argument to the
97 * {@link Ext.data.Record#create data Record create method} in order to
98 * configure the layout of the Records it will produce.</li>
99 * <li>a <b><tt>{@link Ext.data.Store#sortInfo sortInfo}</tt></b> property
100 * which the JsonReader will use to set the {@link Ext.data.Store}'s
101 * {@link Ext.data.Store#sortInfo sortInfo} property</li>
102 * <li>any custom properties needed</li>
106 * Create a new JsonReader
107 * @param {Object} meta Metadata configuration options.
108 * @param {Array/Object} recordType
109 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
110 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
111 * constructor created from {@link Ext.data.Record#create}.</p>
113 Ext.data.JsonReader = function(meta, recordType){
116 * @cfg {String} idProperty [id] Name of the property within a row object
117 * that contains a record identifier value. Defaults to <tt>id</tt>
120 * @cfg {String} successProperty [success] Name of the property from which to
121 * retrieve the success attribute. Defaults to <tt>success</tt>. See
122 * {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
123 * for additional information.
126 * @cfg {String} totalProperty [total] Name of the property from which to
127 * retrieve the total number of records in the dataset. This is only needed
128 * if the whole dataset is not passed in one go, but is being paged from
129 * the remote server. Defaults to <tt>total</tt>.
132 * @cfg {String} root [undefined] <b>Required</b>. The name of the property
133 * which contains the Array of row objects. Defaults to <tt>undefined</tt>.
134 * An exception will be thrown if the root property is undefined. The data
135 * packet value for this property should be an empty array to clear the data
140 successProperty: 'success',
141 totalProperty: 'total'
144 Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
146 Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
148 * This JsonReader's metadata as passed to the constructor, or as passed in
149 * the last data packet's <b><tt>metaData</tt></b> property.
154 * This method is only used by a DataProxy which has retrieved data from a remote server.
155 * @param {Object} response The XHR object which contains the JSON data in its responseText.
156 * @return {Object} data A data block which is used by an Ext.data.Store object as
157 * a cache of Ext.data.Records.
159 read : function(response){
160 var json = response.responseText;
161 var o = Ext.decode(json);
163 throw {message: 'JsonReader.read: Json object not found'};
165 return this.readRecords(o);
169 * TODO: refactor code between JsonReader#readRecords, #readResponse into 1 method.
170 * there's ugly duplication going on due to maintaining backwards compat. with 2.0. It's time to do this.
173 * Decode a JSON response from server.
174 * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
175 * @param {Object} response The XHR object returned through an Ajax server request.
176 * @return {Response} A {@link Ext.data.Response Response} object containing the data response, and also status information.
178 readResponse : function(action, response) {
179 var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
181 throw new Ext.data.JsonReader.Error('response');
184 var root = this.getRoot(o);
185 if (action === Ext.data.Api.actions.create) {
186 var def = Ext.isDefined(root);
187 if (def && Ext.isEmpty(root)) {
188 throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
191 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
195 // instantiate response object
196 var res = new Ext.data.Response({
198 success: this.getSuccess(o),
199 data: (root) ? this.extractData(root, false) : [],
200 message: this.getMessage(o),
204 // blow up if no successProperty
205 if (Ext.isEmpty(res.success)) {
206 throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
212 * Create a data block containing Ext.data.Records from a JSON object.
213 * @param {Object} o An object which contains an Array of row objects in the property specified
214 * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
215 * which contains the total size of the dataset.
216 * @return {Object} data A data block which is used by an Ext.data.Store object as
217 * a cache of Ext.data.Records.
219 readRecords : function(o){
221 * After any data loads, the raw JSON data is available for further custom processing. If no data is
222 * loaded or there is a load exception this property will be undefined.
227 this.onMetaChange(o.metaData);
229 var s = this.meta, Record = this.recordType,
230 f = Record.prototype.fields, fi = f.items, fl = f.length, v;
232 var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
234 v = parseInt(this.getTotal(o), 10);
239 if(s.successProperty){
240 v = this.getSuccess(o);
241 if(v === false || v === 'false'){
246 // TODO return Ext.data.Response instance instead. @see #readResponse
249 records : this.extractData(root, true), // <-- true to return [Ext.data.Record]
250 totalRecords : totalRecords
255 buildExtractors : function() {
259 var s = this.meta, Record = this.recordType,
260 f = Record.prototype.fields, fi = f.items, fl = f.length;
262 if(s.totalProperty) {
263 this.getTotal = this.createAccessor(s.totalProperty);
265 if(s.successProperty) {
266 this.getSuccess = this.createAccessor(s.successProperty);
268 if (s.messageProperty) {
269 this.getMessage = this.createAccessor(s.messageProperty);
271 this.getRoot = s.root ? this.createAccessor(s.root) : function(p){return p;};
272 if (s.id || s.idProperty) {
273 var g = this.createAccessor(s.id || s.idProperty);
274 this.getId = function(rec) {
276 return (r === undefined || r === '') ? null : r;
279 this.getId = function(){return null;};
282 for(var i = 0; i < fl; i++){
284 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
285 ef.push(this.createAccessor(map));
292 * TODO This isn't used anywhere?? Don't we want to use this where possible instead of complex #createAccessor?
294 simpleAccess : function(obj, subsc) {
301 createAccessor : function(){
303 return function(expr) {
304 if(Ext.isEmpty(expr)){
307 if(Ext.isFunction(expr)){
310 var i = String(expr).search(re);
312 return new Function('obj', 'return obj' + (i > 0 ? '.' : '') + expr);
314 return function(obj){
322 * type-casts a single row of raw-data from server
323 * @param {Object} data
324 * @param {Array} items
325 * @param {Integer} len
328 extractValues : function(data, items, len) {
330 for(var j = 0; j < len; j++){
332 var v = this.ef[j](data);
333 values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
340 * @class Ext.data.JsonReader.Error
341 * Error class for JsonReader
343 Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
344 constructor : function(message, arg) {
346 Ext.Error.call(this, message);
348 name : 'Ext.data.JsonReader'
350 Ext.apply(Ext.data.JsonReader.Error.prototype, {
352 'response': 'An error occurred while json-decoding your server response',
353 '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.',
354 '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.',
355 '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.',
356 'root-empty': '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.'