Javascript 余烬数据序列化程序数据映射
我正在使用ember&ember数据来尝试使用来自服务器的json提要。这是我的密码:Javascript 余烬数据序列化程序数据映射,javascript,rest,ember.js,ember-data,Javascript,Rest,Ember.js,Ember Data,我正在使用ember&ember数据来尝试使用来自服务器的json提要。这是我的密码: App = Ember.Application.create(); DS.RESTAdapter.configure( "plurals", { category: 'categories' } ); App.Store = DS.Store.extend({ revision: 12, adapter: DS.RESTAdapter.create({
App = Ember.Application.create();
DS.RESTAdapter.configure(
"plurals", {
category: 'categories'
}
);
App.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.create({
url: 'app'
})
});
App.Router.map(function(){
this.resource('categories');
});
App.CategoriesRoute = Ember.Route.extend({
model: function() {
return App.Category.find();
}
});
var attr = DS.attr;
App.Category = DS.Model.extend({
name: attr('string')
});
现在,这可以在测试服务器上正常工作。
使用以下JSON
{
"categories":[
{
"name":"Beef",
"id":1
},
{
"name":"Pork",
"id":2
}
]
}
但是,在生产环境中,服务器提供以下json:
{
"success":true,
"message":"Request successful",
"total":2,
"data":[
{
"name":"Beef",
"id":1
},
{
"name":"Pork",
"id":2
}
]
}
我一辈子都不知道如何使用序列化程序来使用实时json。任何帮助都将不胜感激。提前谢谢
更新:
后来我尝试编写序列化程序,但它似乎不起作用
见下文
App.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.create({
url: 'app',
serializer: DS.RESTSerializer.extend({
extract: function(loader, json, type, record) {
var root = 'data';
this.sideload(loader, type, json, root);
this.extractMeta(loader, type, json);
if (json[root]) {
if (record) { loader.updateId(record, json[root]); }
this.extractRecordRepresentation(loader, type, json[root]);
}
}
})
})
});
它现在会产生此错误未捕获错误:断言失败:您的服务器返回了一个包含密钥数据的哈希,但您没有该哈希的映射您有2个选项
- 使您的服务器兼容,并让它按照ember data的要求返回json
- 编写自己的适配器/序列化程序以支持此格式
更新:编写自己的序列化程序
更新2:删除未使用的函数
您可以从DS.RESTSerializer
继承并使用此代码更改extract
extract: function(loader, json, type, record) {
var root = 'data';
if (json[root]) {
if (record) { loader.updateId(record, json[root]); }
this.extractRecordRepresentation(loader, type, json[root]);
}
}
这假设请求的内容将始终位于json的数据键下。出于某种原因,提取覆盖似乎不会触发:(您是否从DS.RESTSerializer
继承并在适配器上设置新的序列化程序?您好,我已经用新的序列化程序代码编辑了这个问题,它似乎没有按预期工作。问题是序列化程序不知道接收到的数据类型。我需要多考虑一下。因为序列化程序不能从json推断类型,适配器将需要在发出xhr请求时捕获此信息。