Active Model Serializer formatting JSON display
我正在我的Rails应用程序中使用活动模型序列化程序,我想重构显示:
每当我访问http://localhost:3000/api/users/1时,我都会看到:
1 | {"data":{"id":"1","type":"users","attributes":{"username":"Iggy1"},"relationships":{"items":{"data":[{"id":"1","type":"items"},{"id":"7","type":"items"}]},"lists":{"data":[{"id":"1","type":"lists"},{"id":"8","type":"lists"},{"id":"14","type":"lists"},{"id":"15","type":"lists"},{"id":"17","type":"lists"}]}}}} |
我怎样才能让它看起来像:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | { "data": { "id":"1", "type":"users", "attributes": { "username":"Iggy1" }, "relationships": { "items": { "data": [{ "id":"1", "type":"items" }, { "id":"7", "type":"items" }] }, "lists": { "data": [{ "id":"1", "type":"lists" }, { "id":"8", "type":"lists" }, { "id":"14", "type":"lists" }, { "id":"15", "type":"lists" }, { "id":"17", "type":"lists" }] } } } } |
号
我花了很多时间浏览适配器、渲染和体系结构,但找不到指南。首先,是否可以使它看起来像上面的第二个代码块?第二,如果可能的话,我该怎么做才能改变显示器?
API/用户控制器.rb
1 2 3 4 5 6 7 8 9 10 | def show @user = User.find_by(id: params[:id]) @no_user_found = User.all #other alternative when user ID not found? if @user.nil? flash[:notice] ="No user found" render json: @no_user_found, each_serializer: UserSerializer else render json: @user, each_serializer: UserSerializer end end |
用户序列化程序.rb
1 2 3 4 5 | class UserSerializer < ActiveModel::Serializer attributes :id, :username#, :email has_many :items, through: :lists has_many :lists end |
。
路线.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Rails.application.routes.draw do ActiveModelSerializers.config.adapter = :json_api namespace :api, defaults: { format: :json } do resources :users do resources :lists end resources :lists, only: [] do resources :items, only: [:create, :index, :show, :update] end resources :items, only: [:destroy] end end |
我建议不要使用浏览器,而是使用邮递员
可以使用以下代码以缩进和换行方式呈现它:
1 | [cc]<%= JSON.pretty_generate(your_json_here) %> |
在上面的代码中,请使用: 您的问题是如何设计JSON输出的样式。正如上面@araratan建议的那样,您只能使用它来为您提供可读性。而且在机器中也没有必要让它变得时髦。如果您需要在generate prety json outpur中进行相同的查看