Manually parse json data according to kendo model

时光怂恿深爱的人放手 提交于 2019-12-11 05:28:39

问题


Any built-in ready-to-use solution in Kendo UI to parse JSON data according to schema.model? Maybe something like kendo.parseData(json, model), which will return array of objects?


回答1:


I was searching for something like that and couldn't find anything built-in. However, using Model.set apparently uses each field's parse logic, so I ended up writing this function which works pretty good:

function parse(model, json) {
    // I initialize the model with the json data as a quick fix since
    // setting the id field doesn't seem to work. 
    var parsed = new model(json);
    var fields = Object.keys(model.fields);
    for (var i=0; i<fields.length; i++) {
        parsed.set(fields[i], json[fields[i]]);
    }
    return parsed;
}

Where model is the kendo.data.Model definition (or simply datasource.schema.model), and json is the raw object. Using or modifying it to accept and return arrays shouldn't be too hard, but for my use case I only needed a single object to be parsed at a time.




回答2:


I actually saw your post the day you posted it but did not have the answer. I just needed to solve this problem myself as part of a refactoring. My solution is for DataSources, not for models directly.

kendo.data.DataSource.prototype.parse = function (data) {
    return this.reader.data(data);
    // Note that the original data will be modified. If that is not what you want, change to the following commented line
    // return this.reader.data($.extend({}, data));
}

// ...

someGrid.dataSource.parse(myData);

If you want to do it directly with a model, you will need to look at the DataReader class in kendo.data.js and use a similar logic. Unfortunately, the DataReader takes a schema instead of a model and the part dealing with the model is not extracted in it's own method.



来源:https://stackoverflow.com/questions/30187807/manually-parse-json-data-according-to-kendo-model

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