6

我已经真正进行了搜索,但还没有找到使用序列化程序从不同格式的 JSON 响应中获取对象的体面示例。我不更改 JSON 响应格式的原因在http://flask.pocoo.org/docs/security/#json-security中进行了概述。

我对 javascript 还不是很好,所以我很难理解 serialize_json.js 中的钩子,或者我应该使用映射(我只是不知道)。所以这是我对许多对象的 JSON 响应的示例:

{
  "total_pages": 1, 
  "objects": [
     {
      "is_completed": true, 
      "id": 1, 
      "title": "I need to eat"
    }, 
    {
      "is_completed": false, 
      "id": 2, 
      "title": "Hey does this work"
    }, 
    {
      "is_completed": false, 
      "id": 3, 
      "title": "Go to sleep"
    }, 
  ], 
  "num_results": 3, 
  "page": 1
}

当 ember-data 尝试使用它时,我收到以下错误:

DEBUG: -------------------------------
DEBUG: Ember.VERSION : 1.0.0-rc.1
DEBUG: Handlebars.VERSION : 1.0.0-rc.3
DEBUG: jQuery.VERSION : 1.9.1
DEBUG: -------------------------------
Uncaught Error: assertion failed: Your server returned a hash with the key total_pages but you have no mapping for it 

当您查看我的数据存储代码时,这完全是:

Todos.Store = DS.Store.extend({
    revision: 12,
    adapter: DS.RESTAdapter.create({
        mappings: {objects: "Todos.Todo"},
        namespace: 'api'
    })
});

My question is how do I deal with total_pages, num_results and page? And by deal, I mean ignore so I can just map the objects array.

4

3 回答 3

3

All root properties you return in your JSON result are mapped to a DS.Model in Ember Data. You should not return properties that are not modelled or you should model them.

If you want to get rid of the error you should make an empty model for the properties you don't use.

Read more here

Why are you returning properties you don't want to use? Or is it out of your control?

于 2013-03-11T22:17:10.280 回答
1

Ember is fairly opinionated about how things are done. Ember data is no exception. The Ember team works towards certain standards that it thinks is best, which is, in my opinion, a good thing.

Check out this post on where ember is going. TL;DR because there are so many varying implementations of api calls, they're setting their efforts towards supporting the JSON API.

From my understanding, there is no easy way to do what you're asking. Your best bet is to write your own custom adapter and serialized. This shouldn't be too hard to do, and has been done before. I recommend you having a look at the Tastypie adapter used for Python's Django Tastypie

于 2013-06-09T17:34:55.863 回答
1

The way to accomplish this is with a custom serializer. If all your data is returned from the server in this format you could simply create ApplicationSerializer like this:

DS.RESTSerilizer.extend({
  normalizePayload: function(type, payload) {
     delete payload.total_pages;
     delete payload.num_results;
     delete payload.page;
     return payload;
  }
});

That should allow Ember Data to consume your API seamlessly.

于 2014-04-17T09:03:21.710 回答