6.Core Json – JSON和Ruby
最后更新于:2022-04-01 05:30:58
Ruby有许多与JSON相关的库。下面的例子结合使用了Ruby和JSON。
~~~
require 'json'
class Address
attr_accessor :line1, :city, :state_or_province,
:zip_or_postal_code, :country
def initialize(line1='', city='', state_or_province='',
zip_or_postal_code='', country='')
@line1 = line1
@city = city
@state_or_province = state_or_province
@zip_or_postal_code = zip_or_postal_code
@country = country
end
def to_json
to_hash.to_json
end
def from_json!(str)
JSON.parse(str).each { |var, val| send("#{var}=", val) }
end
private
def to_hash
Hash[instance_variables.map { |var| [var[1..-1].to_sym,
send(var[1..-1])] }]
end
end
~~~
JSON gem的to*json方法将字符串或哈希值转换为JSON。 Address对象的to*json方法通过将它的数据成员转换为哈希值,然后调用to_json的散列来转换地址对象为JSON。为了将地址转换为JSON,请参考下面的列子:
~~~
addr1 = Address.new('555 Main Street', 'Denver', 'CO', '80231', 'US')
puts addr1.to_json
# Outputs the following …
{"line1":"555 Main Street","city":"Denver","state_or_province":"CO","zip_or_postal_code":"80231","country":"US"}
~~~
JSON gem的JSON.parse方法将一个JSON字符串转换为哈希值。地址对象的from_json!方法接收一个JSON字符串,然后调用JSON.parse转换为一个Hash值,并且按照以下方式设置每一个来自哈希的对应数据成员:
~~~
json_addr = <<END
{
"line1" : "999 Broadway", "city" : "Anytown",
"state_or_province" : "CA", "zip_or_postal_code" : "90210",
"country" : "USA"
}
END
addr2 = Address.new
addr2.from_json!(json_addr)
~~~