如何为 Ember 数据创建自定义序列化程序 [英] How to create a custom Serializer for Ember data

查看:15
本文介绍了如何为 Ember 数据创建自定义序列化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 API 返回的 JSON 格式不正确,无法供 Ember 使用.而不是这个(余烬所期待的):

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" }}
]}

所以如果我理解正确的话,我需要创建一个自定义序列化程序来修改 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:我的目标是让 App.Event.find() 工作.目前,我得到 未捕获的错误:断言失败:您的服务器返回了一个密钥为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆