PDA

View Full Version : How to model nested JSON array?



jayg
6 Dec 2011, 2:16 PM
I'm trying to create my first ExtJS Model. I receive a JSON response like this:


{"RESPONSE":
{"TOKEN_ID":"12345",
"STATUS_CODE":0,
"FRUITS":
{"FRUIT":["Apple","Orange","Banana"]}
}
}

I'd like to check the STATUS_CODE value and display the list of fruits in a ComboBox.

I've tried dozens of Model variations, like this:


Ext.define('fruit.model.FruitList', {
extend: 'Ext.data.Model',
fields: [
{name: 'statusCode', mapping: 'STATUS_CODE', type: 'string' }
],
hasMany: {model: 'fruit.model.Fruit', name: 'fruits', associationKey: 'FRUITS', reader: {type: 'json', record: 'FRUIT'}}
});

Ext.define('fruit.model.Fruit', {
extend: 'Ext.data.Model',
fields: [
{name: 'name', mapping: function(v){return v;}}
],
belongsTo: 'fruit.model.FruitList'
});

without success. Any suggestions how to model this? Also, how would I use the "nested" store in a ComboBox? Thanks!

mitchellsimoens
9 Dec 2011, 2:08 PM
First, you need to format your JSON to be readable:


{
"RESPONSE": {
"TOKEN_ID": "12345",
"STATUS_CODE": 0,
"FRUITS": {
"FRUIT": [
"Apple",
"Orange",
"Banana"
]
}
}
}

Since "RESPONSE" is an object and not an array, you can't use it as the root in your reader so you technically only have one field here and that is "RESPONSE". You can use mapping to map a field something like


{ name : 'STATUS_CODE', mapping : 'RESPONSE.STATUS_CODE' }