将Ruby对象序列化为JSON并返回? [英] Serialize Ruby object to JSON and back?

查看:322
本文介绍了将Ruby对象序列化为JSON并返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个对象序列化为JSON,将其写入文件并读回.现在,我希望在.net中有类似json.net之类的东西,并且您可以这样做:

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);

并完成它.您会返回JSON字符串.

and be done with it. You get back the JSON string.

如何在Ruby中执行此操作?没有Rails,没有ActiveRecord,什么都没有.有没有我找不到的宝石?

How do I do this in Ruby? No Rails, no ActiveRecord, no nothing. Is there a gem I can't find?

我安装了JSON gem,并名为:

I installed the JSON gem and called:

puts JSON.generate([obj])

其中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))

我得到的是:

["#<CrawlStep:0x00000001270d70>"]

我在做什么错了?

推荐答案

最简单的方法是制作to_json方法和json_create方法.就您而言,您可以执行以下操作:

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

然后,通过调用JSON.dump(obj)进行序列化,并使用JSON.parse(obj)进行反序列化. to_json中散列的数据部分可以是任何东西,但我喜欢将其保留为new/initialize将获得的参数.如果还需要保存其他内容,则应将其放入此处,然后以某种方式解析出来,然后将其设置在json_create中.

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.

这篇关于将Ruby对象序列化为JSON并返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆