JSON output setup

In the controller, I have response_with:

respond_with(@layer1 , @layer2) 

The JSON output I need is as follows:

 { "LayerOne": [ { "name": "haha", "number":"44" }, // more .... ], "LayerTwo": [ { "name": "James Bond", "score": 20 } // , .... ] } 

So, to get the first section, I write a serializer as follows:

 class Layer1Serializer < ActiveModel::Serializer attributes :number, :name def name object.person.name end end 

And I am modifying the controller so that I can pass ROOT, so it shows in JSON as "LayerOne"

 respond_with(@Layer1, root: 'LayerOne') 

but remember that in the beginning I had two things to go to the controller, so now I canโ€™t figure out how to do this for the second JSON section that says โ€œLayer2โ€

+4
source share
4 answers

You can create the following intermediate class:

 class BothLayers include ActiveModel def initialize(layer1,layer2) @layer1 = layer1 @layer2 = layer2 end attr_accessor :layer1, :layer2 end 

and the following serializer:

 class BothLayersSerializer < ActiveModel::Serializer root false has_many :layer1, key: "LayerOne" has_many :layer2, key: "LayerTwo" end 

Then in your controller:

  both_layers = BothLayers.new(@layer1,@layer2) respond_with( both_layers, serializer: BothLayersSerializer ) 
+6
source

create a new hash and pass the array values โ€‹โ€‹into it.

 respond_with({:LayerOne => @layer1.as_json(:only => [:name, :percentage]), :LayerTwo => @layer2.as_json(:only => [:name, :off_target_by])}) 

I got this json:

 { "LayerOne": [ { "name": "layer1", "percentage": "10.11" }, { "name": "layer 1 bis", "percentage": "1212.0" } ], "LayerTwo": [ { "name": "layer 2", "off_target_by": 2 }, { "name": "layer 2 bis", "off_target_by": 9 } ] } 

hope this helps :)

EDIT 2:

You can create an array serializer to pass in your variables:

 class LayerArraySerializer < ActiveModel::ArraySerializer self.root = false end 

and in your opinion:

 respond_with({:LayerOne => @layer1 , :LayerTwo => @layer2}, :serializer => LayerArraySerializer) 

json print:

 [ [ "LayerOne", [ { "percentage": "10.11", "name": "layer1" }, { "percentage": "1212.0", "name": "layer 1 bis" } ] ], [ "LayerTwo", [ { "off_target_by": 2, "name": "layer 2" }, { "off_target_by": 9, "name": "layer 2 bis" } ] ] ] 
+1
source

Using JBuilder DSL is a great way to solve your problem.

https://github.com/rails/jbuilder

The JSON response you want is implemented as a view giving you full control over how it displays.

+1
source

Railcasts has a great video + text tutorial on AR Serializer, I'm sure you will find your answer there

http://railscasts.com/episodes/409-active-model-serializers

0
source

Source: https://habr.com/ru/post/1469103/


All Articles