如何将响应格式从fast_jsonapi格式更改为AMS gem响应格式

时间:2019-03-19 13:19:12

标签: ruby-on-rails json active-model-serializers fastjsonapi

我想从以下位置更改fast_jsonapi gem的响应格式:

{
    "data": {
        "id": "8",
        "type": "directory",
        "attributes": {
            "firstname": "Naoufal",
            "lastname": "Huster",
        }
    }
}

对此:

{
  "id": "8",
  "firstname": "Naoufal",
  "lastname": "Huster",
}

我正在从使用AMS gem迁移到使用fast_jsonapi,我想使用fast_jsonapi,但在呈现数据时保持AMS的响应json格式相同。

Ruby 2.5.0 导轨5.2.1 fast_jsonapi宝石

2 个答案:

答案 0 :(得分:1)

You can use sparse fieldsets to selectively choose which fields you want.

class MovieSerializer
  include FastJsonapi::ObjectSerializer

  attributes :name, :year
end

serializer = MovieSerializer.new(movie, { fields: { movie: [:name] } })
serializer.serializable_hash

If you need the data flattened even further, you can create a helper method to manually flatten out the JSON or you can try to flatten it using the standard .flatten function on an array or hash depending on your data format. You cannot perform flatten if you've already stringified it into JSON.

答案 1 :(得分:0)

我认为这是不可能的。 <nav class="class-bar"> <ul class="class-bar__menu"> <li class="class-bar__item"> <a [routerLinkActive]="['demo_class demo_class--active']" routerLink = "/xyz">Item1</a> </li> <li class="class-bar__item"> <a [routerLinkActive]="['demo_class demo_class--active']" [routerLink] = "['/abc']">Item2</a> </li> </ul> </nav> 宝石遵循json api标准。

此外,回购中也提出了类似的问题:source