将json解析为对象ruby

时间:2012-10-04 08:18:45

标签: ruby json

我查看了不同的资源,仍然对如何将json格式解析为自定义对象感到困惑,例如

class Resident
  attr_accessor :phone, :addr

  def initialize(phone, addr)
      @phone = phone
      @addr = addr
  end
end    

和JSON文件

{
  "Resident": [
    {
      "phone": "12345",
      "addr":  "xxxxx"
    }, {
      "phone": "12345",
      "addr": "xxxxx"
    }, {
      "phone": "12345",
      "addr": "xxxxx"
    }
  ]
}

将json文件解析为3 Resident对象数组的正确方法是什么?

5 个答案:

答案 0 :(得分:61)

今天我正在寻找将json转换为对象的东西,这就像魅力一样:

person = JSON.parse(json_string, object_class: OpenStruct)

这样,如果响应是数组

,您可以person.education.schoolperson[0].education.school

我将它留在这里因为可能对某人有用

答案 1 :(得分:31)

以下代码更简单:

require 'json'

data = JSON.parse(json_data)
residents = data['Resident'].map { |rd| Resident.new(rd['phone'], rd['addr']) }

答案 2 :(得分:4)

require 'json'

class Resident
    attr_accessor :phone, :addr

    def initialize(phone, addr)
        @phone = phone
        @addr = addr
    end
end

s = '{"Resident":[{"phone":"12345","addr":"xxxxx"},{"phone":"12345","addr":"xxxxx"},{"phone":"12345","addr":"xxxxx"}]}'

j = JSON.parse(s)

objects = j['Resident'].inject([]) { |o,d| o << Resident.new( d['phone'], d['addr'] ) }

p objects[0].phone
"12345"

答案 3 :(得分:2)

我们最近发布了一个解决该问题的Ruby库static_structCheck it out

答案 4 :(得分:0)

如果您正在使用ActiveModel::Serializers::JSON,则可以致电from_json(json),您的对象将与这些值进行映射。

class Person
  include ActiveModel::Serializers::JSON

  attr_accessor :name, :age, :awesome

  def attributes=(hash)
    hash.each do |key, value|
      send("#{key}=", value)
    end
  end

  def attributes
    instance_values
  end
end

json = {name: 'bob', age: 22, awesome: true}.to_json
person = Person.new
person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
person.name # => "bob"
person.age # => 22
person.awesome # => true