PDA

View Full Version : Parsing JSON in List component



BenMajor
16 Mar 2011, 7:24 AM
Hello again,

Sorry for my numerous questions, but I'm trying to get to grips with Sencha Touch, and some of the API docs are a bit unclear.

I would like to know the code to parse the following JSON into a DataStore and then output it as a grouped list:


{
"friends":[
{
"friend":{
"id":"4",
"forename":"Chris",
"surname":"Major",
"verboseName":"Chris Major",
"phoneNumber":"07931655247",
"longitude":"-0.410909",
"latitude":"52.999245",
"email":"major@lincsmps.co.uk",
"lastRefresh":null,
"joinDate":"1294839423"
},
"networks":null,
"approved":"1"
},
{
"friend":{
"id":"2",
"forename":"Marta",
"surname":"Urbanowicz",
"verboseName":"Marta Urbanowicz",
"phoneNumber":"07716021468",
"longitude":"-0.0338518",
"latitude":"52.9773876",
"email":"urb.marta@googlemail.com",
"lastRefresh":null,
"joinDate":"1294836801"
},
"networks":null,
"approved":"1"
}
]
}

As you can see, the root element is 'friends', and then each item has three values ('friend' [an object], 'networks' [an array of objects] and 'approved'). I don't know how to create the relevant data store and generate the List element...

Thanks for your help,
Ben.

markwyner
16 Mar 2011, 12:16 PM
Reference the Ext.data.Reader documentation:

http://dev.sencha.com/deploy/touch/docs/?class=Ext.data.Reader

And here's a basic setup based on that information:


Ext.regModel('Friends', {
fields: ['networks', 'approved'],
proxy: {
type: 'ajax',
url : 'friends.json',
reader: {
type: 'json'
}
},
hasMany: {model: 'Friend', name: 'friend'}
});

Ext.regModel("Friend", {
fields: ['id', 'forename', '...'],
belongsTo: 'Friends'
});

var StoreFriends = new Ext.data.Store({
model: 'Friends',
autoLoad: true,
sorters: 'friend',
getGroupString : function(record) {
return record.get('friend')[0];
}
});

new Ext.List({
store: StoreFriends,
itemTpl: '{verboseName})',
grouped: true
})

I hope that helps.

BenMajor
17 Mar 2011, 3:11 AM
Sincere thanks for your help with this one Mark. That did the trick.

Great help as ever,
Ben.

markwyner
17 Mar 2011, 8:34 AM
Absolutely, Ben. Glad I could help.

Cheers.