38

例如,我查看了不同的资源,但仍然对如何将 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个常驻对象数组的正确方法是什么?

4

5 回答 5

97

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

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

这种方式你可以做,person.education.school或者person[0].education.school如果响应是一个数组

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

于 2015-09-09T02:48:19.247 回答
39

下面的代码更简单:

require 'json'

data = JSON.parse(json_data)
residents = data['Resident'].map { |rd| Resident.new(rd['phone'], rd['addr']) }
于 2012-10-04T08:55:28.883 回答
8

如果您正在使用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
于 2017-07-21T06:43:30.800 回答
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"
于 2012-10-04T08:35:21.380 回答
3

我们最近发布了一个 Ruby 库static_struct来解决这个问题。检查出来

于 2016-01-18T02:57:04.790 回答