我有一个API,它返回的JSON格式不正确,无法使用Ember。 而不是这(烬预期):
{ events: [
{ id: 1, title: "Event 1", description: "Learn Ember" },
{ id: 2, title: "Event 2", description: "Learn Ember 2" }
]}
我明白了:
{ events: [
{ event: { id: 1, "Event 1", description: "Learn Ember" }},
{ event: { id: 2, "Event 2", description: "Learn Ember 2" }}
]}
因此,如果我理解正确,我需要创建一个自定义序列化程序来修改JSON。
var store = DS.Store.create({
adapter: DS.RESTAdapter.create({
serializer: DS.Serializer.create({
// which hook should I override??
})
})
});
我已经阅读了与DS.Serializer相关的代码注释,但我无法理解如何实现我想要的...
我该怎么做?
ps:我的目标是让App.Event.find()
工作。目前,我得到Uncaught Error: assertion failed: Your server returned a hash with the key 0 but you have no mapping for it
。这就是我需要修复收到的JSON的原因。
编辑:这就是我现在的工作原理:
extractMany: function(loader, json, type, records) {
var root = this.rootForType(type),
roots = this.pluralize(root);
json = reformatJSON(root, roots, json);
this._super(loader, json, type, records);
}
答案 0 :(得分:12)
我假设响应仅包含ID,并且您尝试提取它们。
您需要子类DS.JSONSerializer
,它提供了处理JSON有效负载的基本行为。特别是,您需要覆盖extractHasMany
挂钩:
// elsewhere in your file
function singularize(key) {
// remove the trailing `s`. You might want to store a hash of
// plural->singular if you deal with names that don't follow
// this pattern
return key.substr(0, key.length - 1);
}
DS.JSONSerializer.extend({
extractHasMany: function(type, hash, key) {
return hash[key][singularize(key)].id;
}
})