首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在FastJson接口中使用CollectionSerializer?

如何在FastJson接口中使用CollectionSerializer?
EN

Stack Overflow用户
提问于 2019-11-04 20:12:41
回答 1查看 244关注 0票数 0

在我工作的地方,我将API代码更新为FastJson (https://github.com/Netflix/fast_jsonapi)。“旧”代码使用的是ActiveModel,并且有ActiveModel::Serializer::CollectionSerializer.new。我不知道如何将这段代码“翻译”成FastJson接口。

我已经在FastJson文档中搜索过关于集合序列化(https://github.com/Netflix/fast_jsonapi#collection-serialization)的内容,但是我不理解这个例子。

代码语言:javascript
运行
复制
class API::Messages::MessagesSerializer < ActiveModel::Serializer
  attributes :id, :name, :description

  attribute :chats do
    ActiveModel::Serializer::CollectionSerializer.new(
      object.user_chats, serializer: API:Messages::ChatUserSerializer
    )
  end
end 
EN

回答 1

Stack Overflow用户

发布于 2019-11-04 20:36:59

当集合被传递到序列化程序中时,它将完美地处理该集合,不需要配置任何额外的东西。以下是序列化程序

代码语言:javascript
运行
复制
class API::Messages::MessagesSerializer
  include FastJsonapi::ObjectSerializer
  attributes :id, :name, :description

  attributes :chats do |message|
    API::Messages::ChatsSerializer.new(message. user_chats)
  end
end

class API::Messages::ChatsSerializer
  include FastJsonapi::ObjectSerializer
  attributes ... # add attribute/logic as you want for single chat object
end

你的控制器应该是这样的

代码语言:javascript
运行
复制
def show
  render json: API::Messages::MessagesSerializer.new(@message).serialized_json, status: :ok
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58693246

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档