HTTParty - JSON 到强类型对象
是否可以让 HTTParty 将 GET 的结果反序列化为强类型 ruby 对象?例如
class Myclass
include HTTParty
end
x = Myclass.get('http://api.stackoverflow.com/1.0/questions?tags=HTTParty')
puts x.total
puts x.questions[0].title
,现在它将其反序列化为哈希值。
puts x["total"]
我的问题实际上是 HTTParty 是否支持此 OTB,而不是通过安装额外的 gem。
编辑:
我对 Ruby 还很陌生,但我记得类字段都是私有的,因此需要通过 getter/setter 方法来访问它们。那么也许这个问题不是一个有效的问题?
Is it possible to have HTTParty deserialize the results from a GET to a strongly typed ruby object? For example
class Myclass
include HTTParty
end
x = Myclass.get('http://api.stackoverflow.com/1.0/questions?tags=HTTParty')
puts x.total
puts x.questions[0].title
Right now it deserializes it into a hash
puts x["total"]
My question is actually if HTTParty supports this OTB, not by installing additional gems.
Edit:
I'm still new to Ruby, but I recall that class fields are all private so they would need to be accessed through getter/setter methods. So maybe this question isn't a valid one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只需要方法语法,则可以使用开放结构。
一个可能的缺点是这个对象是完全开放的,如果你调用它不存在的方法,它只会返回 nil (如果你调用 setter,它将创建 setter 和 getter)
If you are just wanting method syntax, you can use an open struct.
A possible downside is that this object is totally open such that if you invoke a nonexistent method on it, it will just return nil (if you invoke a setter, it will create both the setter and getter)
听起来您希望
Myclass::get
的返回值是Myclass
的实例。如果是这种情况,您可以缓存 HTTP 请求的返回值并实现method_missing
以从该哈希返回值:这并不完全是您所要求的,因为它只适用于一层深度 -即,
x.questions[0].title
需要是x.questions[0][:title]
也许你可以想出这个答案和约书亚溪的优势开放结构。
我还应该指出,如果您的方法没有被命名为
get
,则所有方法别名欺骗都是不必要的。It sounds like you want the return value of
Myclass::get
to be an instance ofMyclass
. If that's the case, you could cache the return value from the HTTP request and implementmethod_missing
to return values from that hash:This isn't exactly what you asked for, because it only works one level deep — i.e.,
x.questions[0].title
would need to bex.questions[0][:title]
Perhaps you could come up with some hybrid of this answer and Joshua Creek's to take advantage of OpenStruct.
I should also point out that all the method aliasing trickery isn't necessary if your method doesn't have to be named
get
.