Serialize Ruby object to JSON and back?
I want to serialize an object to JSON, write it to file and read it back. Now I'd expect something like in .net where you have json.net or something like that and you do:
JsonSerializer.Serialize(obj);
and be done with it. You get back the JSON string.
How do I do this in Ruby? No Rails, no ActiveRecord, no nothing. Is there a gem 开发者_开发知识库I can't find?
I installed the JSON gem and called:
puts JSON.generate([obj])
where obj is an object like:
class CrawlStep
attr_accessor :id, :name, :next_step
def initialize (id, name, next_step)
@id = id
@name = name
@next_step = next_step
end
end
obj = CrawlStep.new(1, 'step 1', CrawlStep.new(2, 'step 2', nil))
All I get back is:
["#<CrawlStep:0x00000001270d70>"]
What am I doing wrong?
The easiest way is to make a to_json
method and a json_create
method. In your case, you can do this:
class CrawlStep
# Insert your code here (attr_accessor and initialize)
def self.json_create(o)
new(*o['data'])
end
def to_json(*a)
{ 'json_class' => self.class.name, 'data' => [id, name, next_step] }.to_json(*a)
end
end
Then you serialize by calling JSON.dump(obj)
and unserialize with JSON.parse(obj)
. The data part of the hash in to_json
can be anything, but I like keeping it to the parameters that new
/initialize
will get. If there's something else you need to save, you should put it in here and somehow parse it out and set it in json_create
.
精彩评论