2017-08-29 18 views
1

我有一個JSON對象,如下所示:定製包裝JSON到了Virtus模型?

{ 
    "id":"10103", 
    "key":"PROD", 
    "name":"Product", 
    "projectCategory":{ 
     "id":"10000", 
     "name":"design", 
     "description":"" 
    } 
} 

和看起來像下面這樣的了Virtus模型:

class Project 
    include Virtus.model 

    attribute :id, Integer 
    attribute :key, String 
    attribute :name, String 

    attribute :category, String #should be the value of json["projectCategory"]["name"] 

end 

一切都行了罰款以外試圖映射Project.categoryjson["projectCategory"]["name"]

所以總結束了Virtus對象我去找應該是這樣的:

"id"  => "10103", 
"key"  => "PROD", 
"name"  => "Product", 
"category" => "design" 

現在我創建一個模型實例與Project.new(JSON.parse(response))或基本JSON響應的哈希值。我該如何自定義地圖了Virtus一些屬性,以我的JSON響應?

回答

0

所以我最終搞清楚你可以重寫self.new方法讓你去哈希值嵌套你通過你的了Virtus模型。

我結束了做這工作得很好如下:

class Project 
    include Virtus.model 

    attribute :id,  Integer 
    attribute :name,  String 
    attribute :key,  String 
    attribute :category, String 

    def self.new(attributes) 
    new_attributes = attributes.dup 

    # Map nested obj "projectCategory.name" to Project.category 
    if attributes.key?("projectCategory") and attributes["projectCategory"].key?("name") 
     new_attributes[:'category'] = attributes["projectCategory"]["name"] 
    end 

    super(new_attributes) 
    end 

end