PDA

View Full Version : JSON encoding nested models



bdvr
2 May 2011, 8:18 AM
Hello,

I'm looking for a way to take a nested model (with hasMany associations) and JSON encode it--basically convert a nested model into a JSON string. I've been looking through the library, and I can't seem to find any part of the API that accomplishes this.

I remember reading that the proxies implement this functionality, but looking through the code for the various proxies, it seems that they do not implement nested models. I came across "getRecordData" in the base writer, and it looks like it only goes one node deep, and doesn't appear to be overridden anywhere. Too bad--I could just call that to get the nested data, then call Ext.encode on it. Maybe I'm overlooking something?

If there's nothing in ST that accomplishes this, then it looks like I'll be writing it myself. Thoughts, anyone? Thanks in advance.




write: function(request) {
var operation = request.operation,
records = operation.records || [],
ln = records.length,
i = 0,
data = [];

for (; i < ln; i++) {
data.push(this.getRecordData(records[i]));
}
return this.writeRecords(request, data);
},


getRecordData: function(record) {
return record.data;
}

bdvr
2 May 2011, 9:54 AM
I ended up just writing my own helper functions to accomplish this. If anyone knows of a more "official" way to go about it, I'd love to know.

Here's the code in case it is of help to anyone. The only association I bothered implementing was "hasMany". I'm using these to get the object graph, then I call Ext.encode.



//Gets the entire nested object graph for a model
getModelData: function (model) {
var data = {};

for (var p in model.data) {
data[p] = model.data[p];
}

for (var i = 0; i < model.associations.length; i++) {
if (model.associations.items[i].type == "hasMany") {
var name = model.associations.items[i].name;
data[name] = this.getStoreData(model[name]());
}
}

return data;
},

//Gets the entire nested object graph for each model in a store
getStoreData: function (store) {
var count = store.getCount();
var values = [];

for (var i = 0; i < count; i++) {
values.push(this.getModelData(store.data.items[i]));
}

return values;
}