Ruby2.5.0/Rails5.2.1下:如何让fast_jsonapi输出AMS格式响应
解决fast_jsonapi输出格式匹配AMS扁平结构的问题
我刚帮你梳理了从AMS迁移到fast_jsonapi后保持扁平JSON格式的几种可行方案,针对你的Ruby 2.5.0 + Rails 5.2.1环境完全适用:
方案1:重写序列化器的serializable_hash方法(推荐)
fast_jsonapi默认输出符合JSON:API规范的嵌套结构,我们可以直接在序列化器里重写serializable_hash方法,把id和attributes合并成扁平结构:
class DirectorySerializer include FastJsonapi::ObjectSerializer attributes :firstname, :lastname def serializable_hash(options = nil) # 获取默认的JSON:API结构数据 json_api_data = super[:data] # 合并id与attributes生成扁平哈希 { id: json_api_data[:id], **json_api_data[:attributes] } end end
在控制器中使用时,直接调用serializable_hash即可返回扁平结构:
def show directory = Directory.find(params[:id]) render json: DirectorySerializer.new(directory).serializable_hash end
如果是集合数据(比如索引接口返回多个Directory),只需要稍作调整遍历处理:
def serializable_hash(options = nil) json_api_hash = super json_api_hash[:data].map do |item| { id: item[:id], **item[:attributes] } end end
方案2:控制器层直接处理输出
如果不想修改序列化器,也可以在控制器中先解析fast_jsonapi的默认输出,再转换为扁平结构:
def show directory = Directory.find(params[:id]) # 获取默认JSON:API格式的响应 raw_response = DirectorySerializer.new(directory).serialized_json parsed_data = JSON.parse(raw_response)["data"] # 组装成期望的扁平结构 flat_response = { "id" => parsed_data["id"], **parsed_data["attributes"] } render json: flat_response end
这种方式适合临时需求,要是多个接口都需要,建议把转换逻辑抽成一个控制器Concern或者辅助方法。
方案3:全局配置转换方法(谨慎使用)
如果你的项目中大部分序列化器都需要扁平结构,可以全局配置fast_jsonapi的转换方法:
- 在
config/initializers/fast_jsonapi.rb中添加配置:
FastJsonapi.configure do |config| config.transform_method = :flatten_response end
- 扩展fast_jsonapi的序列化器模块,实现转换方法:
module FastJsonapi module ObjectSerializer def flatten_response(hash) data = hash[:data] if data.is_a?(Array) data.map { |item| { id: item[:id], **item[:attributes] } } else { id: data[:id], **data[:attributes] } end end end end
⚠️ 注意:全局配置会影响所有序列化器,如果你有部分接口需要保留JSON:API原生格式,这种方式就不太适合了。
内容的提问来源于stack exchange,提问作者Naoufal El Hassnaoui
相关产品推荐
相关产品推荐

