Serialize a Ruby object for JSON and vice versa?

I want to serialize an object in JSON, write it to a file, and read it. Now I would expect something like .net where you have json.net or something like that:

JsonSerializer.Serialize(obj); 

and get it over with. You are returning a JSON string.

How to do it in Ruby? No rails, no ActiveRecord, nothing. Is there a gem that I cannot find?

I installed the JSON gem and called:

 puts JSON.generate([obj]) 

where obj is an object of type:

 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 is:

 ["#<CrawlStep:0x00000001270d70>"] 

What am I doing wrong?

+4
source share
1 answer

The easiest way is to make the to_json method and the 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) . Part of the hash data in to_json can be anything, but I like to save it in the parameters that new / initialize will get. If you need something else, you should put it here and somehow parse it and set it to json_create .

+14
source

Source: https://habr.com/ru/post/1333881/


All Articles