您的位置:首页 > 编程语言 > Ruby

Ruby on Rails emoji表情通过json返回

2016-03-25 00:00 351 查看
摘要: 解决emoji通过json返回不显示

原因:



大概意思是:emoji表情是5位字符 而to_json/as_json最多支持4个字符,导致返回的emoji不完整,客户端就不会识别,导致乱码。
解决方法:
在config/initializers文件夹下新建patches.rb 文件:
config/initializers/patches.rb文件内容:
module ActiveSupport::JSON::Encoding
class << self
def escape(string)
if string.respond_to?(:force_encoding)
string = string.encode(::Encoding::UTF_8, :undef => :replace).force_encoding(::Encoding::BINARY)
end
json = string.gsub(escape_regex) { |s| ESCAPED_CHARS[s] }
json = %("#{json}")
json.force_encoding(::Encoding::UTF_8) if json.respond_to?(:force_encoding)
json
end
end
end

或者
module ActiveSupport
module JSON
module Encoding
class << self
def escape(string)
::JSON.generate([string])[1..-2]
end
end
end
end
end


参考链接:
http://stackoverflow.com/questions/5123993/json-encoding-wrongly-escaped-rails-3-ruby-1-9-2/8339255#8339255
http://stackoverflow.com/questions/683989/how-do-you-deal-with-the-conflict-between-activesupportjson-and-the-json-gem/3285570#3285570
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ruby on rails emoji json