Ruby 使用 JSON 序列化结构

2024-04-26

我正在尝试将一个简单的结构序列化为 JSON,它工作正常,但我无法让它从 JSON 创建该结构的实例。我正在尝试这样做。

require 'rubygems'
require 'json'

Person = Struct.new(:name, :age)

json = Person.new('Adam', 19).to_json
puts json

me = JSON.load(json)
puts me.name

我得到以下输出:

"#<struct Person name=\"Adam\", age=19>"
/usr/lib/ruby/1.9.1/json/common.rb:148:in `parse': 746: unexpected token at '"#<struct Person name=\"Adam\", age=19>"' (JSON::ParserError)
    from /usr/lib/ruby/1.9.1/json/common.rb:148:in `parse'
    from /usr/lib/ruby/1.9.1/json/common.rb:309:in `load'
    from why.rb:9:in `<main>'

在这种情况下,person.to_json没有做你期望的事。

当你require 'json',JSON 库插入一个#to_json方法上Object如果没有专门的,这是一个后备方案#to_json其他地方提供的方法。这个插入方法 http://ruby-doc.org/stdlib-2.1.3/libdoc/json/rdoc/JSON/Ext/Generator/GeneratorMethods/Object.html与调用基本相同#to_s#to_json在一个物体上。

如果你的Person在这里上课,#to_s输出标准Object#to_s http://ruby-doc.org/core-2.2.0/Object.html#method-i-to_s,默认情况下,它不提供可由 JSON 库解析的字符串。

然而,Struct does提供一个#to_h可用于将该结构转换为Hash, and Hash(在需要 JSON 库时)知道如何生成 JSON 可解析输出。

所以简单地改变:

json = Person.new('Adam', 19).to_json
puts json

to:

person = Person.new('Adam', 19)
puts person.to_h.to_json

会做你所期望的。

(顺便说一句,我实际上建议实施#to_json on the Person直接类作为调用#to_h#to_json违反了得墨忒耳定律 http://en.wikipedia.org/wiki/Law_of_Demeter.)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ruby 使用 JSON 序列化结构 的相关文章

随机推荐