活动模型序列化器和自定义JSON结构 [英] Active Model Serializer and Custom JSON Structure
问题描述
我正在尝试将Active Model Serializer gem与我的API一起使用,尽管我在努力进行一些我认为很简单的事情.
I'm trying to use the Active Model Serializer gem with my API, although I am struggling with something I thought would be pretty simple.
我所有的JSON响应都采用包装格式,每个响应都具有顶级消息和status属性,数据位于content属性内.每个JSON响应都遵循这种格式.
All my JSON responses are in a wrapped format, with every response having a top level message and status property, the data is within the content property. Every JSON response follows this format.
示例
{
'status': statuscode,
'message': message,
'content': { 'object':obj }
}
内容"属性的内容是我要放置序列化器输出的位置.我的文章列表等
The contents of the "content" property is where I would like to place the output of the Serializer. My lists of articles, etc.
我还是不知道该怎么做?
I cannot figure out how to do this though?
任何帮助将不胜感激.
推荐答案
如果您不介意状态和消息散列位于散列中,则可以使用元键.
IF You dont mind your status and messages hashes being inside a hash you can use a meta key.
(来自 https://github.com/rails-api/active_model_serializers/tree/0-8稳定)
render :json => @posts, :serializer => CustomArraySerializer, :meta => {:total => 10}
=>
{
"meta": { "total": 10 },
"posts": [
{ "title": "Post 1", "body": "Hello!" },
{ "title": "Post 2", "body": "Goodbye!" }
]
}
或者,如果您需要它们作为顶级键,则可以使用SubClass ArraySerializer并覆盖as_json以允许其合并到您的键中.
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
然后
render :json @object, :serializer => YourCustomArraySerializer
这篇关于活动模型序列化器和自定义JSON结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!