Rails 3.2:使用JSON序列化中的空字符串替换空值 [英] Rails 3.2: Replace null values with empty string from json serialization

查看:141
本文介绍了Rails 3.2:使用JSON序列化中的空字符串替换空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rails 3.2 序列化,将ruby对象转换为json.

I am using Rails 3.2 serialization to convert ruby object to json.

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

For Example, I have serialized ruby object to following json

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

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

Using following serialize method in my class Relationship < ActiveRecord::Base

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

我需要将空值替换为空字符串,即响应json中的空双引号.

I need to replace null values with empty strings i.e. empty double quotes, in response json.

我该如何实现?

最好的问候,

推荐答案

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

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

-编辑-

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

As per jdoe's comment, if you only want to include some fields in your json response, I prefer doing it as:

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

这篇关于Rails 3.2:使用JSON序列化中的空字符串替换空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆