2013-03-11 88 views
1

我想轉換一個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

回答

1

你應該能夠實現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的實例,它們將分別響應userTypeIddescription方法。您可以通過在重寫的方法中調用super並將userTypeIddescription的值傳遞給您自己的類來獲得此實例。

編輯: - 更正類名

PS:有一個看看ActiveResource#load方法,詳細瞭解如何獲得的屬性生成getter方法。

+0

太棒了@和!你的解決方案工作,現在我可以使用UserType類。我看到你使用ActiveSupport而不是ActiveResource,應該使用哪一種?他們之間有什麼區別?我試圖使用ActiveSupport,但我收到一個錯誤。感謝幫助=)! – danilodeveloper 2013-03-12 13:08:26

+0

哎呀..那裏有一個錯字。它實際上是ActiveResource。 – 2013-03-12 21:12:15

+0

np = D tks再次!!! – danilodeveloper 2013-03-15 00:17:24