0

我正在努力处理一些内部带有哈希的数组。我想将它们解析成一个新对象,但不知道该怎么做。

这是数据:

[
  {
    "name"  => "itemHref",
    "value" => "https://192.168.75.145:8281/api/workflows/16da1fa1-7c8b-4602-8d53-17fc5e1fa3ff/"
  },
  {
    "name"  => "id",
    "value" => "16da1fa1-7c8b-4602-8d53-17fc5e1fa3ff"
  },
  {
    "name"  => "categoryName",
    "value" => "FinanzInformatik"
  },
  {
    "name"  => "canExecute",
    "value" => "true"
  },
  {
    "name"  => "categoryHref",
    "value" => "https://192.168.75.145:8281/api/catalog/System/WorkflowCategory/ff8080813b90a145013b90cac51b0006/"
  },
  {
    "name"  => "description",
    "value" => "bekommt alle VMs"
  },
  {
    "name"  => "name",
    "value" => "getAllVms"
  },
  {
    "name"  => "type",
    "value" => "Workflow"
  },
  {
    "name"  => "canEdit",
    "value" => "true"
  }
]

而且,这是我的代码:

require 'rest-client'
require 'json'

class Workflow
  def initialize(itemHref, id, categoryName, canExecute, categoryHref, description, name, type, canEdit)
    @itemHref = itemHref
    @id = id
    @categoryName = categoryName
    @canExecute = canExecute
    @categoryHref = categoryHref
    @description = description
    @name = name
    @type = type
    @canEdit = canEdit
  end
end

json_string = RestClient.get( "http://vcoadmin:vcoadmin@192.168.75.145:8280/api/workflows", :content_type => 'application/json', :accept => 'application/json')
parsed = JSON.parse(json_string)

parsed.each do |a, b|
 if(b.class == Array)
  b.flatten.each do |c|
   p c['attributes']
   #c['attributes'].each
  {
    |f| p f['name'], f['value'] }
  end
 end
end

如何将哈希值放入对象中?我根据值的标识符“名称”来考虑一些事情。

有任何想法吗?

4

2 回答 2

0

假设不应更改属性的顺序:

Workflow.new(*parsed.map {|attr| attr['value']})
于 2013-01-02T21:18:59.893 回答
0

我将实现一个可以用哈希初始化的 PORO。因此,您可以将哈希直接传递给创建工作流。

可以看到一个例子:http: //pullmonkey.com/2008/01/06/convert-a-ruby-hash-into-a-class-object/

于 2013-01-02T21:56:53.263 回答