我正在覆盖to_json
当我在我的模型上调用to_json时,我得到以下结果:

{ "integer1": "23", "integer2": "2", "integer3": "4", ... }

我希望to_json返回:
{ "Something": "23", "SomethingElse": "2", "AnotherThing": "4", ... }

我有一个包含键及其映射的数组:
"integer1" => "Something", "integer2" => "SomethingElse", "integer3" => "AnotherThing", ....

我怎样才能做到这一点?

最佳答案

转换您的model instance into a hash
将哈希转换为所需的值:

h1 = { "integer1" => "23", "integer2" => "2", "integer3" => "4" }
h2 = { "integer1" => "Something", "integer2" => "SomethingElse", "integer3" => "AnotherThing" }
desired = Hash[ h1.map{ |k,v| [ h2[k], v ] } ]

从中获取json:
json = desired.to_json

08-05 02:11