【问题标题】:Rails 3.2: Replace null values with empty string from json serializationRails 3.2:用 json 序列化中的空字符串替换空值
【发布时间】:2012-06-04 09:55:11
【问题描述】:

我正在使用 Rails 3.2 serialization 将 ruby​​ 对象转换为 json。

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

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

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

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

我需要用空字符串替换空值,即空双引号,以响应 json。

我怎样才能做到这一点?

最好的问候,

【问题讨论】:

  • why do what to do that,如果它有nil,你会进一步看到什么问题?
  • Objective C 不能将 null 识别为像 true/false 这样的特殊字符串。

标签: ruby-on-rails ruby json serialization ruby-on-rails-3.2


【解决方案1】:

可能不是最好的解决方案,但受到answer的启发

def as_json(opts={})
  json = super(opts)
  Hash[*json.map{|k, v| [k, v || ""]}.flatten]
end

-- 编辑--

根据 jdoe 的评论,如果您只想在 json 响应中包含一些字段,我更喜欢这样做:

def as_json(opts={})
  opts.reverse_merge!(:only => [:type, :id, :followed_id])
  json = super(opts)
  Hash[*json.map{|k, v| [k, v || ""]}.flatten]
end

【讨论】:

  • 这不会导致出现json中的所有属性(这显然不是作者想要的)?我大约在第一行。第二个看起来无可挑剔。
  • 酷,谢谢!目前 as_json 在所有 activeRecord 类中实现。有没有办法将此方法放入父类,即 ActiveRecord::Base
  • 如果值 v 为 false,这将不起作用。结果,您拥有的任何布尔字段为 false 都将转换为“”。您可以改为: Hash[*json.map{|k, v| [k, (v.nil? ? "" : v)]}.flatten]
【解决方案2】:

我没有看到这里的问题。只需通过|| 运营商即可:

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

【讨论】:

  • 感谢 jdoe,其实我想要一些通用代码用于所有对象序列化
【解决方案3】:

使用以下方法,您将获得修改后的哈希或 json 对象。它将用 nill 替换空白字符串。需要在参数中传递哈希。

def json_without_null(json_object)
  if json_object.kind_of?(Hash)
    json_object.as_json.each do |k, v|
      if v.nil?
        json_object[k] = ""
      elsif  v.kind_of?(Hash)
        json_object[k] = json_without_null(v)
      elsif v.kind_of?(Array)
        json_object[k] = v.collect{|a|  json_without_null(a)}
      end
    end
  end
  json_object
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2016-04-14
    相关资源
    最近更新 更多