复杂属性3.2.12
问题描述:
我想转换一个web服务响应转换成在我的Rails应用程序对象,我收到了以下JSON:复杂属性3.2.12
{
"id": 1,
"status": true,
"password": "123",
"userType": {
"description": "description",
"userTypeId": 1
},
"email": "[email protected]"
}
我想要的用户类型转换在用户类型Ruby类属性是这样的:
class UserType
attr_accessor :userTypeId, :description
end
我使用的ActiveResource与web服务进行沟通,我试图用属性方法转换USERTYPE JSON属性为用户等级和积分类,但属性方法不接受复杂类型,只有字符串,整数e et c ...
如何将userType(webservice response)转换为UserType Ruby Class?
Rails的3.2.12和Ruby 1.9.3p194
答
你应该能够实现userType
作为实例方法。
class MyResource < ActiveResource::Base
self.site = "http://api.example.com/"
def userType
UserType.new(userTypeId: super.userTypeId, description: super.description)
end
end
这工作,因为的ActiveResource自动为每个在属性中的键的“吸气”方法哈希您传递到类的构造函数。当被调用的属性方法对应一个散列值时,ActiveResource返回一个自动生成的类MyResource::UserType
的实例,它们将分别响应userTypeId
和description
方法。您可以通过在重写的方法中调用super
并将userTypeId
和description
的值传递给您自己的类来获得此实例。
编辑: - 更正类名
PS:有一个看看ActiveResource#load方法,详细了解如何获得的属性生成getter方法。
太棒了@和!你的解决方案工作,现在我可以使用UserType类。我看到你使用ActiveSupport而不是ActiveResource,应该使用哪一种?他们之间有什么区别?我试图使用ActiveSupport,但我收到一个错误。感谢帮助=)! – danilodeveloper 2013-03-12 13:08:26
哎呀..那里有一个错字。它实际上是ActiveResource。 – 2013-03-12 21:12:15
np = D tks再次!!! – danilodeveloper 2013-03-15 00:17:24