You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Grape Entity框架中为循环元素设别名以生成指定JSON?

在Grape Entity中为循环元素应用别名的解决方案

我来帮你搞定这个Grape Entity的别名配置问题!你想要把返回的字段从product改成Product、country_name改成CountryName,其实用Grape Entity自带的:as参数就能轻松实现,而且这个配置会自动应用到循环的每个元素上,完全匹配你的需求。

修改后的代码示例

module API
  module Entities
    class Example < Grape::Entity
      # 为product字段设置别名为Product
      expose(:product, as: 'Product') do
        # 为country_name字段设置别名为CountryName
        expose(:country_name, as: 'CountryName') do |product, options|
          product.country.name
        end
      end
    end
  end
end

关键改动说明

  • 外层的product字段:在expose方法中添加:as: 'Product'参数,就能把返回的键名从小写product替换成你需要的Product
  • 内层的country_name字段:同样通过:as: 'CountryName'参数,将返回键名改为CountryName
  • 当你用这个实体序列化产品集合(也就是循环处理多个元素)时,每个元素都会自动套用这套别名规则,最终生成你期望的JSON格式:
    [{"Product":{"CountryName":4848}},{"Product":{"CountryName":700}}]
    

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:36:27