How to read nested JSON structure with a Sencha Touch Data Model?

不想你离开。 提交于 2019-12-02 21:12:26

Ran into a similar problem recently..I think.

You need to specify the mapping to the data you want in your model. For example :

Ext.regModel('Album', {
fields: [
    {name: 'artist_name', mapping: 'album.artist.name'},
    {name: 'artist_token', mapping: 'album.artist.token'},
    {name: 'album_name', mapping: 'album.name'},
    {name: 'token', mapping: 'album.token'},
    {name: 'small_cover_url', mapping: 'album.covers.s'},
    {name: 'large_cover_url', mapping: 'album.covers.l'}
]/*,
getGroupString : function(record) {
    return record.get('artist.name')[0];
},*/

});

consumes this JSON:

   {
  "album":{
     "covers":{
        "l":"http://media.audiobox.fm/images/albums/V3eQTPoJ/l.jpg?1318110127",
        "m":"http://media.audiobox.fm/images/albums/V3eQTPoJ/m.jpg?1318110127",
        "s":"http://media.audiobox.fm/images/albums/V3eQTPoJ/s.jpg?1318110127"
     },
     "artist":{
        "name":"New Order",
        "token":"OyOZqwkN"
     },
     "name":"(The Best Of)",
     "token":"V3eQTPoJ"
  }

},


I've added a converter to allow the template access the data in the model consistently regardless if a single object or an array is returned.

Ext.regModel("ParentModel", {
        fields: [
            {name: 'parentId', type: 'string'},
            {name: 'children', convert: 
            function(value, record) {
                if (value.child) {
                    if (value.child instanceof Array) {
                        return value.child;
                    } else {
                        return [value.child]; // Convert to an Array 
                    }
                }

                return value.child;
            }
        }
        ],

        proxy: {
            type: 'ajax',
            url : 'models.json',
            reader: {
                type: 'json',
                root: 'parents.parent' // this works fine
            }
        }
    });

Note: I don't actually need to define the ChildrenModel. I guess I can get away without defining it as Sencha must be automatically type converting it.

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