1

我有一个如下所示的 JSON 对象:

{  
   "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 响应?

4

1 回答 1

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
于 2017-08-29T21:15:16.463 回答