Active Model Serializer and Custom JSON Structure

好久不见. 提交于 2019-12-05 10:51:41

IF You dont mind your status and messages hashes being inside a hash you can use a meta key.

(from https://github.com/rails-api/active_model_serializers/tree/0-8-stable)

render :json => @posts, :serializer => CustomArraySerializer, :meta => {:total => 10}

=> 
 {
  "meta": { "total": 10 },
  "posts": [
    { "title": "Post 1", "body": "Hello!" },
    { "title": "Post 2", "body": "Goodbye!" }
  ]
}

Or if you need them to be top level keys you can SubClass ArraySerializer and overwrite as_json to allow it to merge in your keys.

def as_json(*args)
    @options[:hash] = hash = {}
    @options[:unique_values] = {}

    hash.merge!(@options[:top_level_keys]) if @options.key?(:top_level_keys)

    root = @options[:root]
    if root.present?
      hash.merge!(root => serializable_array)
      include_meta(hash)
      hash
    else
      serializable_array
    end
  end 

then just

render :json @object, :serializer => YourCustomArraySerializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!