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宝石似乎使它看起来像您必须编写自己的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"库,请执行以下操作:
To use the 'json' library:
require 'json'
要将对象转换为JSON(这三种方式等效):
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屋!