Strange JSON behavior? [closed]

2020-07-25 23:07发布

问题:

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 7 years ago.

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)

It fails as well, returning false. Looking further it doesn't seem that json_create is being called.

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?

回答1:

This change in behavior in p392 is due to a security fix. See the p392 release announcement for more details.

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)