奇怪的JSON行为? [英] Strange JSON behavior?
问题描述
我正在尝试将对象转换为JSON,然后再次对其进行解析.问题是,当我解析JSON字符串时,剩下的是散列而不是原始对象.我在 json.rubyforge.com 中找到了一个简单的示例,并尝试了它:
I'm trying to convert an object to JSON and then parse it again. The problem is, when I parse the JSON string I'm left with a Hash and not my original object. I found this simple example at json.rubyforge.com and tried it:
require 'json'
class Range
def to_json(*a)
{
'json_class' => self.class.name,
'data' => [ first, last, exclude_end? ]
}.to_json(*a)
end
def self.json_create(o)
new(*o['data'])
end
end
puts JSON.parse((1..10).to_json) == (1..10)
它也失败,返回false
.进一步看,似乎没有调用json_create
.
It fails as well, returning false
. Looking further it doesn't seem that json_create
is being called.
在这一点上,我认为我必须丢失一些简单的东西,否则我会在某个地方遇到错误.我正在使用Ruby 1.9.3.有人有什么想法吗?
At this point I'm figuring I have to be missing something dead simple or I've run into a bug somewhere. I'm using Ruby 1.9.3. Anyone have any ideas?
推荐答案
p392中的这种行为变化是由于修复.有关更多信息,请参见 p392发布公告.详细信息.
This change in behavior in p392 is due to a security fix. See the p392 release announcement for more details.
您的代码在调用JSON.parse
时添加了:create_additions
选项:
Your code works with the addition of the :create_additions
option in your call to JSON.parse
:
require 'json'
class Range
def to_json(*a)
{
'json_class' => self.class.name,
'data' => [ first, last, exclude_end? ]
}.to_json(*a)
end
def self.json_create(o)
new(*o['data'])
end
end
puts JSON.parse((1..10).to_json, :create_additions => true) == (1..10)
这篇关于奇怪的JSON行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!