Ruby使用JSON序列化结构 [英] Ruby serialize struct with JSON
问题描述
我正在尝试将一个简单的结构序列化为可以正常工作的JSON,但是我无法从JSON中创建该结构的实例.这就是我试图做到的方式.
I am trying to serialize a simple struct to JSON which works fine, but I can't get it to create an instance of that struct from the JSON. Here is how I am trying to do it.
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
并没有达到您的期望.
In this case, person.to_json
is not doing what you expect.
当您使用require 'json'
时,JSON库会在Object
上插入#to_json
方法,如果其他地方没有提供专门的#to_json
方法,则该方法会作为备用方法. 此插入的方法基本上是与在对象上调用#to_s#to_json
相同.
When you require 'json'
, the JSON library inserts a #to_json
method on Object
that is a fallback if there's no specialized #to_json
method provided elsewhere. This inserted method is basically the same as calling #to_s#to_json
on an object.
对于这里的Person
类,#to_s
输出标准Object#to_s
,默认情况下,该标准不提供JSON库可解析的字符串.
In the case of your Person
class here, #to_s
outputs the standard Object#to_s
, which, by default, doesn't provide a string parseable by the JSON library.
但是,Struct
确实提供了#to_h
方法,可用于将该结构转换为Hash
,并且Hash
(根据需要JSON库)知道如何生成JSON可解析的输出.
However, Struct
does provide a #to_h
method that can be used to convert that struct to a Hash
, and Hash
is (upon requiring the JSON library) aware of how to generate a JSON parseable output.
因此只需更改:
json = Person.new('Adam', 19).to_json
puts json
收件人:
person = Person.new('Adam', 19)
puts person.to_h.to_json
将按照您的期望进行操作.
will do what you expect.
(顺便说一句,我实际上建议直接在Person
类上实现#to_json
,因为调用#to_h#to_json
违反了法律特米特.)
(An aside, I would actually recommend implementing #to_json
on the Person
class directly as calling #to_h#to_json
violates the Law of Demeter.)
这篇关于Ruby使用JSON序列化结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!