将JSON转换为RESTAdapter EmberJS的适当格式 [英] Transform JSON to an appropriate format for RESTAdapter EmberJS

查看:121
本文介绍了将JSON转换为RESTAdapter EmberJS的适当格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从我们的API接收到一个JSON,格式如下:

I receive a JSON from our API that has the following format

[
  {
    "id": 45,
    "name": "Pasta",
    "_order": 0,
    "is_hidden": null,
    "is_list": false
  },
  {
    "id": 46,
    "name": "Salads",
    "_order": 1,
    "is_hidden": null,
    "is_list": false
  },
  {
    "id": 47,
    "name": "Dessert",
    "_order": 2,
    "is_hidden": null,
    "is_list": false
  }
];

我看到它标准的RESTAdapter有无效的格式,我需要先把模型的名字。在我的例子中,应该是这样的:

I see that it has invalid format for standard RESTAdapter and I need to put the name of the model first. In my example it should probably be like:

{
  "category":
    [
      {
        "id": 45,
        "name": "Pasta",
        "_order": 0,
        "is_hidden": null,
        "is_list": false
      },
      {
        "id": 46,
        "name": "Salads",
        "_order": 1,
        "is_hidden": null,
        "is_list": false
      },
      {
        "id": 47,
        "name": "Dessert",
        "_order": 2,
        "is_hidden": null,
        "is_list": false
      }
    ]
  }

那么如何让它看起来像我的适配器?看来我应该使用 DS.RESTSerializer ,但我无法弄清楚我应该覆盖哪个方法...

So how to make it look this way in my adapter? It seems like I should use DS.RESTSerializer, but I can't figure out which method I should override...

推荐答案

我今天早些时候遇到这个问题。一个很好的干净的方法来修复它是为您的ApplicationSerializer定义一个
normalizePayload方法。它被覆盖,所以你不会影响任何其他东西。

I ran into this issue earlier today. A nice clean way to fix it is to define a normalizePayload method for your ApplicationSerializer. It's made to be overwritten, so you aren't affecting anything else.

例如

App.ApplicationSerializer = DS.RESTSerializer.extend({
    normalizePayload: function(type, payload) {
        return { category: payload };
    }
}

如果您只想处理一些有效内容,那么只需在其中添加一个条件。

If you want to do this on only some of the payloads processed then you just add a conditional inside it.

App.ApplicationSerializer = DS.RESTSerializer.extend({
    normalizePayload: function(type, payload) {
        if (type.toString() === 'App.Category') {
            return { category: payload };
        }
    }
}

有关normalizePayload方法的更多信息,请参阅 http://emberjs.com/api/data/classes/DS.RESTSerializer.html#method_normalizePayload

For more info on the normalizePayload method see http://emberjs.com/api/data/classes/DS.RESTSerializer.html#method_normalizePayload

这篇关于将JSON转换为RESTAdapter EmberJS的适当格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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