Rails 3.2:用 json 序列化中的空字符串替换 null 值

2024-05-19

我正在使用 Rails 3.2序列化 http://www.simonecarletti.com/blog/2010/04/inside-ruby-on-rails-serializing-ruby-objects-with-json/将 ruby​​ 对象转换为 json。

例如,我已将 ruby​​ 对象序列化为以下 json

{
  "relationship":{
    "type":"relationship",
    "id":null,
    "followed_id": null
  }
}

在我的类关系中使用以下序列化方法ActiveRecord::基础

def as_json(opts = {})
  {
   :type        => 'relationship',
   :id          => id,
   :followed_id => followed_id
  }
end

我需要在响应 json 中用空字符串(即空双引号)替换 null 值。

我怎样才能实现这个目标?

此致,


我在这里没有看到问题。只需通过||操作员:

def as_json(opts = {})
  {
   :type        => 'relationship',
   :id          => id || '',
   :followed_id => followed_id || ''
  }
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails 3.2:用 json 序列化中的空字符串替换 null 值 的相关文章

随机推荐