没有JSON root的Ember.js REST适配器

Ric*_*ard 7 javascript api json ember.js ember-data

Ember.js REST适配器期望JSON返回为:

{
    "person": {
        "first_name": "Barack",
        "last_name": "Obama",
        "is_person_of_the_year": true
    }
}
Run Code Online (Sandbox Code Playgroud)

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

{
    "first_name": "Barack",
    "last_name": "Obama",
    "is_person_of_the_year": true
}
Run Code Online (Sandbox Code Playgroud)

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

更新: 基于Sherwin Yu的回答,这是我想出的,似乎到目前为止工作:https://gist.github.com/richardkall/5910875

Kit*_*nde 15

你也可以将它标准化为ember期望的东西.

App.PersonSerializer = DS.RESTSerializer.extend({
  normalizePayload: function(type, payload) {
    var typeKey = type.typeKey;
    return {
      typeKey: payload
    }
  }
});
Run Code Online (Sandbox Code Playgroud)


She*_* Yu 8

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

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

目前,它看起来像这样:

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]);
  }
},
Run Code Online (Sandbox Code Playgroud)

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

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

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