ruby-on-rails – 将XML字符串转换为Rails中的哈希
发布时间:2020-12-16 22:35:30 所属栏目:百科 来源:网络整理
导读:我使用一些返回xml的服务: response = HTTParty.post(service_url)response.parsed_response = "ntResultnsuccessntruen/successn/Result" 我需要将这个字符串转换成哈希.这样的东西 response.parsed_response.to_hash= {:result = { :success = true
我使用一些返回xml的服务:
response = HTTParty.post(service_url) response.parsed_response => "nt<Result>n<success>ntruen</success>n</Result>" 我需要将这个字符串转换成哈希.这样的东西 response.parsed_response.to_hash => {:result => { :success => true } } 这样做的方法 解决方法
内置的
from_xml Rails哈希方法将精确地做你想要的.为了让你的response.parsed_response正确映射到一个哈希,你需要gsub()的换行符:
hash = Hash.from_xml(response.parsed_response.gsub("n","")) hash #=> {"Result"=>{"success"=>"true"}} 在解析Rails中的散列的上下文中,String类型的对象从一般编程的角度来看比来自Symbol的对象要多.但是,您可以将Rails symbolize_keys方法应用于输出: symbolized_hash = hash.symbolize_keys #=> {:Result=>{"success"=>"true"}} 如你所见,symbolize_keys不对任何嵌套哈希进行操作,但是您可以遍历内部哈希值并应用symbolize_keys. 拼图的最后一块是将字符串“true”转换为布尔值true. AFAIK,没有办法在你的哈希中做到这一点,但是如果你正在迭代/操作它,你可能会实现像suggested in this post这样的解决方案: def to_boolean(str) return true if str == "true" return false if str == "false" return nil end 基本上,当您到达内键值对时,您应该将值to_boolean()应用于当前设置为“true”的值.在您的示例中,返回值为布尔值true. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |