[英]Active Model Serializer and Custom JSON Structure
我正在嘗試使用我的API使用Active Model Serializer gem,盡管我正在努力處理我認為非常簡單的事情。
我的所有JSON響應都是包裝格式,每個響應都有一個頂級消息和狀態屬性,數據在content屬性中。 每個JSON響應都遵循此格式。
例
{
'status': statuscode,
'message': message,
'content': { 'object':obj }
}
“content”屬性的內容是我想放置Serializer輸出的地方。 我的文章列表等
雖然我無法弄清楚怎么做?
任何幫助將不勝感激。
如果你不介意你的狀態和消息哈希在哈希中,你可以使用元鍵。
(來自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!" }
]
}
或者,如果您需要它們作為頂級鍵,您可以使用SubClass ArraySerializer並覆蓋as_json以允許它在您的鍵中合並。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.