我有以下工作representer
为平面JSON工作:
# song_representer_spec.rb
require 'rails_helper'
require "representable/json"
require "representable/json/collection"
class Song < OpenStruct
end
class SongRepresenter < Representable::Decorator
include Representable::JSON
include Representable::JSON::Collection
items class: Song do
property :id
nested :attributes do
property :title
end
end
end
RSpec.describe "SongRepresenter" do
it "does work like charm" do
songs = SongRepresenter.new([]).from_json(simple_json)
expect(songs.first.title).to eq("Linoleum")
end
def simple_json
[{
id: 1,
attributes: {
title: "Linoleum"
}
}].to_json
end
end
我们现在正在实现JSONAPI 1.0的规范,我无法弄清楚如何实现一个能够解析以下json的代表:
{
"data": [
"type": "song",
"id": "1",
"attributes":{
"title": "Linoleum"
}
]
}
提前感谢您的提示和建议
更新
Gist包含工作解决方案
答案 0 :(得分:1)
require 'representable/json'
class SongRepresenter < OpenStruct
include Representable::JSON
property :id
property :type
nested :attributes do
property :title
end
end
class AlbumRepresenter < Representable::Decorator
include Representable::JSON
collection :data, class: SongRepresenter
end
hash = {
"test": 1,
"data": [
"type": "song",
"id": "1",
"attributes":{
"title": "Linoleum"
}
]
}
decorator = AlbumRepresenter.new(OpenStruct.new).from_json(hash.to_json)
您现在可以迭代数据数组并访问SongRepresenter属性:
2.2.1 :046 > decorator = AlbumRepresenter.new(OpenStruct.new).from_json(hash.to_json)
=> #<OpenStruct data=[#<SongRepresenter id="1", type="song", title="Linoleum">]>
2.2.1 :047 > decorator.data
=> [#<SongRepresenter id="1", type="song", title="Linoleum">]
请注意使用hash或JSON.parse(hash.to_json)
的区别2.2.1 :049 > JSON.parse(hash.to_json)
=> {"test"=>1, "data"=>[{"type"=>"song", "id"=>"1", "attributes"=>{"title"=>"Linoleum"}}]}
2.2.1 :050 > hash
=> {:test=>1, :data=>[{:type=>"song", :id=>"1", :attributes=>{:title=>"Linoleum"}}]}
因此,使用AlbumRepresenter.new(OpenStruct.new).from_hash(hash)不起作用,因为符号化键。