Ruby 对象和 JSON 序列化(不带 Rails) [英] Ruby objects and JSON serialization (without Rails)
问题描述
我正在尝试了解 Ruby 中的 JSON 序列化格局.我是 Ruby 新手.
I'm trying to understand the JSON serialization landscape in Ruby. I'm new to Ruby.
如果您不使用 Rails,是否有任何好的 JSON 序列化选项?
Is there any good JSON serialization options if you are not working with Rails?
这似乎是这个答案的去向(到 Rails)如何将 Ruby 对象转换为 JSON
That seems to be where this answer goes (to Rails) How to convert a Ruby object to JSON
json gem 似乎让您看起来必须编写自己的 to_json 方法.我无法让 to_json 使用数组和哈希(文档说它适用于这些)json gem 是否有理由不仅仅反映在对象上并使用默认的序列化策略?这不是 to_yaml 的工作原理吗(在这里猜测)
The json gem seems to make it look like you have to write your own to_json method. I haven't been able to get to_json to work with arrays and hashes (documentation says it works with these) Is there a reason the json gem doesn't just reflect over the object and use a default serialization strategy? Isn't this how to_yaml works (guessing here)
推荐答案
要使 JSON 库可用,您可能需要从包管理器安装 libjson-ruby
.
For the JSON library to be available, you may have to install libjson-ruby
from your package manager.
要使用json"库:
require 'json'
将对象转换为 JSON(这 3 种方式是等效的):
To convert an object to JSON (these 3 ways are equivalent):
JSON.dump object #returns a JSON string
JSON.generate object #returns a JSON string
object.to_json #returns a JSON string
将 JSON 文本转换为对象(这两种方式是等效的):
To convert JSON text to an object (these 2 ways are equivalent):
JSON.load string #returns an object
JSON.parse string #returns an object
对于来自您自己的类的对象会更困难一些.对于下面的类,to_json 将产生类似 ""#<A:0xb76e5728>""
.
It will be a bit more difficult for objects from your own classes. For the following class, to_json will produce something like ""#<A:0xb76e5728>""
.
class A
def initialize a=[1,2,3], b='hello'
@a = a
@b = b
end
end
这可能是不可取的.为了有效地将您的对象序列化为 JSON,您应该创建自己的 to_json 方法.为此, from_json 类方法将很有用.你可以像这样扩展你的类:
This probably isn't desirable. To effectively serialise your object as JSON, you should create your own to_json method. To go with this, a from_json class method would be useful. You could extend your class like so:
class A
def to_json
{'a' => @a, 'b' => @b}.to_json
end
def self.from_json string
data = JSON.load string
self.new data['a'], data['b']
end
end
您可以通过从JSONable"类继承来自动执行此操作:
You could automate this by inheriting from a 'JSONable' class:
class JSONable
def to_json
hash = {}
self.instance_variables.each do |var|
hash[var] = self.instance_variable_get var
end
hash.to_json
end
def from_json! string
JSON.load(string).each do |var, val|
self.instance_variable_set var, val
end
end
end
然后就可以使用object.to_json
序列化为JSON 和object.from_json!string
将保存为 JSON 字符串的保存状态复制到对象中.
Then you can use object.to_json
to serialise to JSON and object.from_json! string
to copy the saved state that was saved as the JSON string to the object.
这篇关于Ruby 对象和 JSON 序列化(不带 Rails)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!