没有 JSON 根的 Ember.js REST 适配器 [英] Ember.js REST Adapter without JSON root

查看:19
本文介绍了没有 JSON 根的 Ember.js REST 适配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ember.js REST Adapter 期望将 JSON 返回为:

The Ember.js REST Adapter expects the JSON to be returned as:

{
    "person": {
        "first_name": "Barack",
        "last_name": "Obama",
        "is_person_of_the_year": true
    }
}

但我的 API 返回的数据没有根元素:

But my API returns the data without a root element:

{
    "first_name": "Barack",
    "last_name": "Obama",
    "is_person_of_the_year": true
}

是否可以自定义 REST 适配器以便它接受我的 JSON 数据?现在它显示断言失败:您的服务器返回了一个密钥为 0 的哈希,但您没有映射"

Is it possible to customize the REST Adapter so that it accepts my JSON data? Right now it's showing "Assertion failed: Your server returned a hash with the key 0 but you have no mapping for it"

更新:基于以下宣伟的回答,这就是我想出的,到目前为止似乎有效:https://gist.github.com/richardkall/5910875

UPDATE: Based on Sherwin Yu's answer below, this is what I came up with, seems to work so far: https://gist.github.com/richardkall/5910875

推荐答案

是的,您可以编写自己的自定义 REST 适配器.查看 JSONSerializer 中的源代码, RESTSerializer(扩展了 JSONSerializer),以及REST 适配器.

Yes, you can write your own custom REST adapter. Take a look at the source code in the JSONSerializer, RESTSerializer (which extends the JSONSerializer), and the REST adapter.

基本上,您需要覆盖 JSONSerializer 中的 extract* 方法.

Basically, the you need to override the extract* methods from the JSONSerializer.

目前,它看起来像这样:

Currently, it looks something like this:

extract: function(loader, json, type, record) {
  var root = this.rootForType(type);

  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]);
  }
},

注意它如何检查 json[root] -- 您必须根据预期的 API 响应编写自定义方法.

Notice how it checks json[root] -- you'd have to write your custom method based on your expected API response.

另一种方法是预处理"来自 API 的 json 以使用根元素.您可以通过找出哪些方法调用 extract*(将 json 传递给它)并在此之前修改 json 以包含根元素来完成此操作.

Another approach would be to "preprocess" the json from the API to use a root element. You could do this by finding out what methods call extract* (which passes it the json) and before it does so, modify the json to contain the root element.

希望对您有所帮助,如果不清楚,请告诉我.

Hope this helps, please let me know if it's unclear.

这篇关于没有 JSON 根的 Ember.js REST 适配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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