Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / data / writer / Json.js
1 /**
2  * @class Ext.data.writer.Json
3  * @extends Ext.data.writer.Writer
4  * @ignore
5  */
6 Ext.define('Ext.data.writer.Json', {
7     extend: 'Ext.data.writer.Writer',
8     alternateClassName: 'Ext.data.JsonWriter',
9     alias: 'writer.json',
10     
11     /**
12      * @cfg {String} root The key under which the records in this Writer will be placed. Defaults to <tt>undefined</tt>.
13      * Example generated request, using root: 'records':
14 <pre><code>
15 {'records': [{name: 'my record'}, {name: 'another record'}]}
16 </code></pre>
17      */
18     root: undefined,
19     
20     /**
21      * @cfg {Boolean} encode True to use Ext.encode() on the data before sending. Defaults to <tt>false</tt>.
22      * The encode option should only be set to true when a {@link #root} is defined, because the values will be
23      * sent as part of the request parameters as opposed to a raw post. The root will be the name of the parameter
24      * sent to the server.
25      */
26     encode: false,
27     
28     /**
29      * @cfg {Boolean} allowSingle False to ensure that records are always wrapped in an array, even if there is only
30      * one record being sent. When there is more than one record, they will always be encoded into an array.
31      * Defaults to <tt>true</tt>. Example:
32      * <pre><code>
33 // with allowSingle: true
34 "root": {
35     "first": "Mark",
36     "last": "Corrigan"
37 }
38
39 // with allowSingle: false
40 "root": [{
41     "first": "Mark",
42     "last": "Corrigan"
43 }]
44      * </code></pre>
45      */
46     allowSingle: true,
47     
48     //inherit docs
49     writeRecords: function(request, data) {
50         var root = this.root;
51         
52         if (this.allowSingle && data.length == 1) {
53             // convert to single object format
54             data = data[0];
55         }
56         
57         if (this.encode) {
58             if (root) {
59                 // sending as a param, need to encode
60                 request.params[root] = Ext.encode(data);
61             } else {
62                 //<debug>
63                 Ext.Error.raise('Must specify a root when using encode');
64                 //</debug>
65             }
66         } else {
67             // send as jsonData
68             request.jsonData = request.jsonData || {};
69             if (root) {
70                 request.jsonData[root] = data;
71             } else {
72                 request.jsonData = data;
73             }
74         }
75         return request;
76     }
77 });