我有一个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.category映射到json["projectCategory"]["name"]之外,一切都很顺利。
所以总的来说,我要查找的end Virtus对象应该如下所示:
"id" => "10103",
"key" => "PROD",
"name" => "Product",
"category" => "design"现在,我正在使用Project.new(JSON.parse(response))或基本上是json响应的散列创建一个模型实例。如何自定义将Virtus的一些属性映射到我的json响应?
发布于 2017-08-30 05:15:16
因此,我最终发现您可以覆盖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
endhttps://stackoverflow.com/questions/45943777
复制相似问题