简体   繁体   English

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

[英]Rails 3.2: Replace null values with empty string from json serialization

I am using Rails 3.2 serialization to convert ruby object to json. 我使用Rails 3.2 序列化将ruby对象转换为json。

For Example, I have serialized ruby object to following json 例如,我已将ruby对象序列化为以下json

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

Using following serialize method in my class Relationship < ActiveRecord::Base 在我的类Relationship < ActiveRecord :: Base中使用以下序列化方法

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

I need to replace null values with empty strings ie empty double quotes, in response json. 我需要用空字符串替换空值,即空双引号,以响应json。

How can I achieve this? 我怎样才能做到这一点?

Best Regards, 最好的祝福,

Probably not the best solution, but inspired by this answer 可能不是最好的解决方案,但受到这个答案的启发

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

-- Edit -- - 编辑 -

As per jdoe's comment, if you only want to include some fields in your json response, I prefer doing it as: 根据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

I don't see the problem here. 我没有在这里看到问题。 Just make it via || 只需通过|| operator: 运营商:

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

using below method you will get modified hash or json object. 使用下面的方法,您将获得修改的哈希或json对象。 it will replace blank string with nill. 它将用nill替换空字符串。 need to pass the hash in parameter. 需要在参数中传递哈希值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM