0

JSON で生成された文字列に属性名を保持させる方法はありますか? このモデルから:

class Person
    attr_accessor :name

    def self.json_create(o)
       new(*o['data'])
    end

    def to_json(*a)
       { 'json_class' => self.class.name, 'data' => [name] }.to_json(*a)
   end 
end

JSON は次の文字列を生成します。

{
    "json_class": "Person",
    "data": ["John"]
}

しかし、私はこのような文字列が欲しかった:

{
    "json_class": "Person",
    "data":
    {
        "name" : "John"
    }
}

それを行い、その名前で属性にアクセスできる方法はありますか? お気に入り:

person.name
4

1 に答える 1

1

「名前」を指定する代わりに、完全な属性を渡すことができます。

def to_json(*a)
  { 'json_class' => self.class.name, 'data' => attributes }.to_json(*a)
end 

特定の属性にフィルターをかけたい場合は、次のようにします。

def to_json(*a)
  attrs_to_use = attributes.select{|k,v| %[name other].include?(k) }
  { 'json_class' => self.class.name, 'data' => attrs_to_use }.to_json(*a)
end 

そして、「名前」だけを使いたい場合は、それを書き留めてください:)

def to_json(*a)
  { 'json_class' => self.class.name, 'data' => {:name => name} }.to_json(*a)
end 

アップデート

すべての属性を処理する初期化子を作成する方法を明確にするために、次のようにすることができます。

class Person
  attr_accessor :name, :other

  def initialize(object_attribute_hash = {})
    object_attribute_hash.each do |k, v| 
      public_send("#{k}=", v) if attribute_names.include?(k)
    end
  end

  def attribute_names
    %[name other] # modify this to include all publicly assignable attributes
  end

  def attributes
    attribute_names.inject({}){|m, attr| m[attr] = send(attr); m}
  end

  def self.json_create(o)
    new(o['data'])
  end

  def to_json(*a)
    { 'json_class' => self.class.name, 'data' => attributes }.to_json(*a)
  end 
end
于 2012-12-03T17:04:05.010 に答える