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

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

问题描述

Ember.js REST适配器期望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"

更新:
根据下面的Sherwin Yu的回答,这是我想出来的,似乎工作到目前为止: 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.

另一种方法是预处理json从API中使用根元素。您可以通过查找调用 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天全站免登陆