ruby-on-rails - 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
解决方案
在阅读了一些 GitHub 问题后,似乎“属性”嵌套来自 JSON API 规范并且是预期的行为: https ://jsonapi.org/format/#document-resource-objects
这个问题很有帮助: https ://github.com/rails-api/active_model_serializers/issues/2202
看起来像一个功能,而不是一个错误。
推荐阅读
- javascript - 滤波器内的多个 IF 条件
- r - 时间序列,使用季度,但给我一条错误消息
- javascript - 如何获取具有某个属性的所有元素的值
- hadoop - Hadoop/HDFS:put 命令失败 - 没有这样的文件或目录
- mongodb - 如何使用 mongo-go-driver 在 Mongodb 文档中设置 TTL 索引?
- selenium - 无法定位元素 | 路径 | Selenium 网络驱动程序
- r - 如何在R中随时间递归计算平均值
- typescript - 为什么我们在打字稿函数类型定义中需要参数名称?
- c# - 带有连接的 Linq 需要按 ID 区分不同的行
- python-3.x - (a >=0) % 5 有什么问题,因为它给了我 1 而不是 0