我希望能够自动将
JSON对象解析为实例变量.例如,使用此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}
我希望能够这样做:
json.shots_count
并输出:
150
我怎么可能这样做?
解决方法
你绝对应该使用类似json [“shots_counts”]的东西,但如果你真的需要客观化的哈希,你可以为此创建一个新类:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。