我正在使用 Rails 3.2 serialization将 ruby 对象转换为 json。
例如,我已经将 ruby 对象序列化为以下 json
{
"relationship":{
"type":"relationship",
"id":null,
"followed_id": null
}
}
在我的类 Relationship < ActiveRecord::Base 中使用以下序列化方法
def as_json(opts = {})
{
:type => 'relationship',
:id => id,
:followed_id => followed_id
}
end
我需要用空字符串替换空值,即空双引号,以响应 json。
我怎样才能做到这一点?
最好的问候,
最佳答案
我没有看到这里的问题。只需通过 ||
运算符即可:
def as_json(opts = {})
{
:type => 'relationship',
:id => id || '',
:followed_id => followed_id || ''
}
end
关于ruby-on-rails - rails 3.2 : Replace null values with empty string from json serialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10811628/