ohler55 / oj

Optimized JSON
http://www.ohler.com/oj
MIT License
3.12k stars 250 forks source link

Behavior with Oj.default_options of create_additions: true #918

Closed mkdynamic closed 4 weeks ago

mkdynamic commented 2 months ago

When passing create_additions: true to the Oj.default_options, I expected that option to be applied to the JSON parsing APIs, but it seems to be ignored.

Oj.default_options = {create_additions: true}
Oj.optimize_rails

class Foo
  def initialize(data)
    @data = data
  end

  def as_json(*pargs, **kwargs, &blk)
    {
      "json_class" => self.class.name,
      "data" => @data
    }.as_json(*pargs, **kwargs, &blk)
  end

  def self.json_create(object, *)
    self.new(object["data"])
  end
end

Actual behavior:

foo_json = Foo.new("bar").to_json
puts(foo_json)
# => {"json_class":"Foo","data":"bar"}

foo = JSON.parse(foo_json)
puts(foo)
# => {"json_class"=>"Foo", "data"=>"bar"}

foo = ActiveSupport::JSON.decode(foo_json)
puts(foo)
# => {"json_class"=>"Foo", "data"=>"bar"}

Expected behavior:

foo_json = Foo.new("bar").to_json
puts(foo_json)
# => {"json_class":"Foo","data":"bar"}

foo = JSON.parse(foo_json)
puts(foo)
# => <Foo:0x... @data="bar">

foo = ActiveSupport::JSON.decode(foo_json)
puts(foo)
# => <Foo:0x... @data="bar">

Is this a bug or am I doing something wrong?

ohler55 commented 2 months ago

Have you looked at the :create_id option. The :create_id and :create_additions are options in the JSON that Oj also supports.

ohler55 commented 4 weeks ago

No response, closing.