Serialize Ruby object to JSON and back?

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-22 12:47:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4569329/serialize-ruby-object-to-json-and-back

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!