使用emberjs POST非常规JSON

时间:2013-12-18 11:45:50

标签: json ember.js ember-data

我正在尝试通过ember框架将JSON发布到api,但是我的api JSON没有遵循ember约定。这就是我要发布的内容:

[
  {
    "id": 1,
    "name": "Mary Kelly",
    "email": "mk@gmail.com",

    "subjects": ["1","2"]
  }
]

Ember希望如此:

{
  "user": {
    "id": 1
    "name": "Mary Kelly",
    "subjects": ["1", "2"],
          },

  "subjects": [{
    "id": "1",
    "name": "History"
  }, {
    "id": "2",
    "name": "Maths"
  }]
}

因此,我需要一个自定义序列化程序来发布帖子,并进行所有其他CRUD操作。这就是我所拥有的:

App.UserSerializer = DS.RESTSerializer.extend({
  extractSingle: function(store, type, payload, id, requestType) {
    var subjects = payload.subjects,
        subjectIds = subjects.mapProperty('id');

    var p = {};
    p.user = payload;
    p.user.subjects = subjectIds;
    p.subjects = subjects;


    console.log('extractSingle', JSON.stringify(p));
    return this._super(store, type, p, id, requestType);
  },

  extractArray: function(store, type, payload, id, requestType) {
    var p = { users: [], subjects: [] };
    for (var i = 0; i < payload.length; i++) {
      var user = payload[i];
      var subjects = user.subjects,
          subjectIds = subjects.mapProperty('id');

      for (var j = 0; j < subjects.length; j++) {
        p.subjects.push(subjects[j]);
      }

      user.subjects = subjectIds;
      p.users.push(user);
    }

    return this._super(store, type, p, id, requestType);
  }

  serializeIntoHash: function(hash, type, record, options) {
    Ember.merge(hash, this.serialize(record, options));
  }

});

extractSingleextractArray适用于获取请求,但发布的serializeIntoHash函数对我不起作用 - 任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我将其显示为正常工作,根据您实现的序列化哈希,提取*仅在获取请求上运行,序列化为哈希用于PUT / POST

http://emberjs.jsbin.com/OxIDiVU/58/edit