0

我有以下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

4

1 回答 1

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) 不起作用,因为符号化的键。

于 2016-06-14T18:36:59.787 回答