Reading json with key:value in ext.store in sencha touch 2

不羁岁月 提交于 2019-12-11 09:47:40

问题


I'm trying to load a particular json file into a listview; but sencha proxy doesn't seem to understand the key pairs of "CurrencyName" and "Value". I'm clueless on how to associate those two values into usable data.

Here's the json:

{
    "timestamp": 1335294053,
    "base": "USD",
    "rates": {
        "AED": 3.6732,
        "AFN": 48.32,
        "ALL": 106.040001
    }
}

my store:

proxy: {
    type: 'ajax',
    url: 'http://localhost/CurrencyFX/latest.json',
    reader: {
        type: 'json',
        rootProperty: 'rates'
    }
},

my model:

Ext.define('CurrencyFX.model.Currency', {
    extend: 'Ext.data.Model',
    config: {
        fields: [ 'name', 'value' ]
    }
});

回答1:


You'll need to write your own JSON reader subclass to make this work, as the data you are dealing with isn't an array.

Thankfully, doing this is fairly simple. Here is something that should do the job:

Ext.define('Ext.data.reader.Custom', {
    extend: 'Ext.data.reader.Json',
    alias : 'reader.custom',

    getRoot: function(data) {
        if (this.rootAccessor) {
            data = this.rootAccessor.call(this, data);
        }

        var values = [],
            name;

        for (name in data) {
            values.push({
                name: name,
                value: data[name]
            });
        }

        return values;
    }
});

Which will work with the following store configuration:

var store = Ext.create('Ext.data.Store', {
    fields: ['name', 'value'],
    autoLoad: true,
    proxy: {
        type: 'ajax',
        url: '0000.json',
        reader: {
            type: 'custom',
            rootProperty: 'rates'
        }
    }
});

Notice the reader type is now custom.

I tested this locally with your data and it seemed to work just fine.



来源:https://stackoverflow.com/questions/10304941/reading-json-with-keyvalue-in-ext-store-in-sencha-touch-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!