根据kendo模型手动解析json数据

Manually parse json data according to kendo model

Kendo UI 中是否有内置的即用型解决方案来根据 schema.model 解析 JSON 数据? 也许像 kendo.parseData(json, model) 这样的东西会 return 对象数组?

在你 post 编辑它的那天我确实看到了你的 post 但没有答案。作为重构的一部分,我只需要自己解决这个问题。我的解决方案是针对数据源,而不是直接针对模型。

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);

如果您想直接使用模型进行操作,则需要查看 kendo.data.js 中的 DataReader class 并使用类似的逻辑。不幸的是,DataReader 采用模式而不是模型,并且处理模型的部分没有在它自己的方法中提取。

我正在搜索类似的东西,但找不到任何内置的东西。然而,使用 Model.set 显然使用了每个字段的解析逻辑,所以我最终编写了这个工作得很好的函数:

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;
}

其中 modelkendo.data.Model 定义(或简称 datasource.schema.model),json 是原始对象。使用或修改它以接受和 return 数组应该不会太难,但对于我的用例,我一次只需要解析一个对象。