首页 > 解决方案 > ActiveModel 序列化器 JSON 包括“属性”键

问题描述

我正在使用Rails ActiveModel Serializer将 JSON 输出到 API 端点。

我得到这个 JSON 输出:

{
  "data":[
    {
      "id":"396",
      "type":"profiles",
      "attributes":{
        "name":"Impossibles",
        "created-at":"2017-05-11T18:14:06.201-04:00",
        "updated-at":"2018-04-01T13:34:15.905-04:00",
        "website":"http://soundcloud.com/impossibles"
      }
    }
  ]
}

但期望它的格式如下:

{
  "data":[
    {
      "id":"396",
      "type":"profiles",
      "name":"Impossibles",
      "created-at":"2017-05-11T18:14:06.201-04:00",
      "updated-at":"2018-04-01T13:34:15.905-04:00",
      "website":"http://soundcloud.com/impossibles"
    }
  ]
}

试图避免返回的 JSON 中的额外嵌套级别。有没有办法删除“属性”键?

这是我的序列化器:

class ProfileSerializer < ActiveModel::Serializer
    attributes :id, :name, :created_at, :updated_at, :website
end

我的控制器:

def show
  profile = Profile.find(params[:id])
  render json: profile, status: :ok
end

标签: ruby-on-railsjsonrubyserialization

解决方案


在阅读了一些 GitHub 问题后,似乎“属性”嵌套来自 JSON API 规范并且预期的行为: https ://jsonapi.org/format/#document-resource-objects

这个问题很有帮助: https ://github.com/rails-api/active_model_serializers/issues/2202

看起来像一个功能,而不是一个错误。


推荐阅读