Ruby on rails 如何将JSON列表映射到Virtus模型?
我有这样的JSON:Ruby on rails 如何将JSON列表映射到Virtus模型?,ruby-on-rails,ruby,json,Ruby On Rails,Ruby,Json,我有这样的JSON: [ { "id": 1, "createdAt": "2014-05-08T18:05:09-03:00", "updatedAt": "2014-05-08T18:05:09-03:00", }, { "id": 2, "createdAt": "2014-05-08T18:08:39-03:00", "updatedAt": "2014-05-08T18:08:39-03:00", } ] 我正试着把这张申报表绘制成一张地图。我的模型是: cl
[
{
"id": 1,
"createdAt": "2014-05-08T18:05:09-03:00",
"updatedAt": "2014-05-08T18:05:09-03:00",
},
{
"id": 2,
"createdAt": "2014-05-08T18:08:39-03:00",
"updatedAt": "2014-05-08T18:08:39-03:00",
}
]
我正试着把这张申报表绘制成一张地图。我的模型是:
class OrdersCollection
include Virtus.model
attribute :list, Array[OrderCollectionItem]
end
class OrderCollectionItem
include Virtus.model
attribute :id
end
列表
属性始终为空,我无法找到原因
有人能帮我理解如何更好地绘制这张地图吗
它不断地返回我:
NoMethodError。预期response.body响应#to_hash
您的JSON格式不正确。您没有在JSON中定义list属性,因此Virtus不知道如何正确映射到它。请尝试将其格式化为以下格式:
{
"list": [
{
"id": 1,
"createdAt": "2014-05-08T18:05:09-03:00",
"updatedAt": "2014-05-08T18:05:09-03:00",
},
{
"id": 2,
"createdAt": "2014-05-08T18:08:39-03:00",
"updatedAt": "2014-05-08T18:08:39-03:00",
}
]
}
您拥有的不是有效的JSON-请尝试
[{“id”:1,…},{“id”:2,…}]
@urigassi。谢谢,但现在它返回了NoMethodError。预期响应。要响应的正文#to_哈希
抱歉。我确实错误地拒绝了您上一次包含解决方案的编辑。@Larry我又添加了一次。现在,我已经用正确的格式和整个版本更新了代码。已经对了。我收到一个三方的来信。我无法编辑它的JSON在解析出JSON之后,应该有一个数组。您需要定义列表
属性<代码>哈希={list:parsed_json}谢谢!它起作用了。但是有一个表示我的模型的数组没有在解析的json中添加此列表?您可能不需要OrdersCollection,只需在解析的数组上循环并为每个元素创建OrderCollectionItem。我不认为iterate会更好。最终的解决方案是:hash={list:response.body}orders\u collection=OrdersCollection.new(hash)