如何用JSON writer编写结构化数据?

时间:2013-05-02 18:11:11

标签: extjs extjs4 extjs4.2

如何在JSON POST中包含hasOne关联的模型数据?

我的网络API需要结构化数据,格式为:

{
    id: 1234,
    name: 'Aaron Smith',
    address: {
        address1: '1925 Isaac Newton Sq',
        address2: 'Suite 300',
        city: 'Reston',
        state: 'VA',
        zip: 20190
    }
}

1 个答案:

答案 0 :(得分:0)

@nonino

我想我知道怎么做但我也有类似的问题。我实际上无法让我的关联给我相关的数据。无论如何,我在互联网上搜索的是这样的自定义编写器,或者只是在默认编写器中getRecordData:function(记录,操作)

这是我的自定义作家

Ext.define('Wakanda.writer', {

    extend: 'Ext.data.writer.Json',

   // alternateClassName: 'SimplyFundraising.data.WakandaWriter',

    alias: 'writer.wakanda',

    writeAllFields: false,

    getRecordData: function(record,operation) {
        debugger;
        Ext.apply(record.data,record.getAssociatedData());
        debugger;
        var isPhantom = record.phantom === true,
            writeAll = this.writeAllFields || isPhantom,
            nameProperty = this.nameProperty,
            fields = record.fields,
            data = {},
            changes,
            name,
            field,
            key;

        if (writeAll) {
            // console.log("getRecordData1", this, arguments);
            fields.each(function(field){
                if (field.persist) {
                    debugger;
                    name = field[nameProperty] || field.name;
                    data[name] = record.get(field.name);
                } else {

                }

            });
        } else {
            changes = record.getChanges();
            debugger;
            // console.log("getRecordData2", this, arguments, changes);
            for (key in changes) {
                if (changes.hasOwnProperty(key)) {
                    field = fields.get(key);
                    name = field[nameProperty] || field.name;
                    data[name] = changes[key];
                }
            }
            if (!isPhantom) {
                debugger;

                data[record.idProperty] = record.getId();
                if(operation.action !== 'destroy'){
                data[record.stampProperty] = record.get(record.stampProperty);
                }
            }
        }
        return {'__ENTITIES': [data]};
    }

});

我认为密钥在getRecordData中,我有一个语句Ext.apply(record.data,record.getAssociatedData());如果record.getAssociatedData确实返回了您的数据,则Ext.apply语句会将您当前的record.data与record.getAssociatedData合并为1个json文件。至少这是我希望发生的事情。在我正确设置关联之前无法测试。

希望这有帮助, 丹

  getRecordData: function(record,operation) {
        debugger;
        Ext.apply(record.data,record.getAssociatedData());
        debugger;