如何为Ember数据创建自定义序列化程序 [英] How to create a custom Serializer for Ember data
问题描述
我有一个返回未正确格式化为Ember消费的JSON的API。
而不是这个(希望是什么):
I have an API that returns JSON that is not properly formatted for Ember's consumption. Instead of this (what ember is expecting):
{ 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" }}
]}
所以如果我理解正确,我需要创建一个自定义的Serializer来修改JSON。
So if I understood correctly, I need to create a custom Serializer to modify the JSON.
var store = DS.Store.create({
adapter: DS.RESTAdapter.create({
serializer: DS.Serializer.create({
// which hook should I override??
})
})
});
我已经阅读了与DS.Serializer相关的代码注释,但是我不明白实现我想要的...
I've read the code comment related to the DS.Serializer, but I can't understand how to achieve what I want...
我该怎么做?
ps:我的目标是make App.Event.find()
work。目前,我得到未捕获错误:断言失败:您的服务器返回一个带有键0的哈希,但是您没有映射
。这就是为什么我需要修复收到的JSON。
ps: My goal is to make App.Event.find()
work. Currently, I get Uncaught Error: assertion failed: Your server returned a hash with the key 0 but you have no mapping for it
. That's why I need to fix the JSON received.
编辑:现在,这是我的工作原理:
edit: Here's how I made it work, for now:
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);
}
推荐答案
我假设回应只包含ID,并且您正在尝试提取它们。
I am assuming that the responses contain the IDs only, and that you are trying to extract them.
您将希望子类 DS.JSONSerializer
,它提供了处理JSON有效载荷的基本行为。特别是,您将要覆盖 extractHasMany
钩子:
You will want to subclass DS.JSONSerializer
, which supplies the basic behavior for dealing with JSON payloads. In particular, you will want to override the extractHasMany
hook:
// 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;
}
})
这篇关于如何为Ember数据创建自定义序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!