自动将JSON对象映射到Ruby中的实例变量 [英] Automatically Map JSON Objects into Instance Variables in Ruby
本文介绍了自动将JSON对象映射到Ruby中的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够自动将JSON对象解析为实例变量.例如,使用此JSON.
I would like to be able to automatically parse JSON objects into instance variables. For example, with this JSON.
require 'httparty'
json = HTTParty.get('http://api.dribbble.com/players/simplebits') #=> {"shots_count":150,"twitter_screen_name":"simplebits","avatar_url":"http://dribbble.com/system/users/1/avatars/thumb/dancederholm-peek.jpg?1261060245","name":"Dan Cederholm","created_at":"2009/07/07 21:51:22 -0400","location":"Salem, MA","following_count":391,"url":"http://dribbble.com/players/simplebits","draftees_count":104,"id":1,"drafted_by_player_id":null,"followers_count":2214}
我希望能够做到这一点:
I'd like to be able to do this:
json.shots_count
并输出:
150
我怎么可能这样做?
推荐答案
您绝对应该使用类似json["shots_counts"]
的名称,但是如果您确实需要对象化的哈希,则可以为此创建一个新类:
You should definitely use something like json["shots_counts"]
, but if you really need objectified hash, you could create a new class for this:
class ObjectifiedHash
def initialize hash
@data = hash.inject({}) do |data, (key,value)|
value = ObjectifiedHash.new value if value.kind_of? Hash
data[key.to_s] = value
data
end
end
def method_missing key
if @data.key? key.to_s
@data[key.to_s]
else
nil
end
end
end
之后,使用它:
ojson = ObjectifiedHash.new(HTTParty.get('http://api.dribbble.com/players/simplebits'))
ojson.shots_counts # => 150
这篇关于自动将JSON对象映射到Ruby中的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文