如何在子类中使用 Ruby 的 to_json 并包含 super's json?


#!/usr/bin/env ruby
require 'json'
class A
  def to_json(*a)
    { :a => 'a' }.to_json(*a)
  end
end
class B < A
  def to_json(*a)
    super({ :b => 'b' })
  end
end
puts B.new.to_json

生产

{"a":"a"}

我如何让它生产

{"a":"a", "b":"b"}

以合理的方式?

我正在使用 Ruby 1.9.3 和最新的 json gem。

一个相关的问题是:*a到to_json的参数是什么? 我已经搜索了文档无济于事。

>你有两个哈希{:a=>'a'}{:b=>'b'}在两个类中,它们是封装的,即对外界隐藏。我能看到的唯一方法是将 json 字符串解析为哈希并合并它们,然后将结果转换为 json。

class B < A
  def to_json(*a)
    JSON.parse(super).merge({:b=>'b'}).to_json
  end
end

但这里有一个小区别:你正在合并{:a=>'a',:b=>'b'}并得到{"a":"a","b":"b"}

*a 是设置 JSON 格式选项的参数

我最终json_map有不同的方法。

#!/usr/bin/env ruby
require 'json'
class A
  def to_json(*a)
    json_map.to_json(*a)
  end
  def json_map
    { :a => 'a' }
  end
end
class B < A
  def json_map
    map = super
    map[:b] = 'b'
    map
  end
end
puts B.new.to_json

也许有一个更漂亮的解决方案,但这有效。

最新更新