Rails使用UTF-8呈现JSON响应

时间:2015-01-06 10:25:39

标签: ruby-on-rails ruby json encoding

我正在尝试使用Rails构建一个API并且到目前为止表现相当不错,但是现在我添加了一个带有变音符号的记录我遇到了一个问题,我无法再渲染JSON而且我不能弄清楚如何解决我的问题。 以下是日志所说的内容:

 Completed 500 Internal Server Error in 40ms

JSON::GeneratorError (source sequence is illegal/malformed utf-8):
  app/controllers/api/v1/raids_controller.rb:8:in `index'


  Rendered /usr/local/lib/ruby/gems/2.1.0/gems/actionpack-   
4.1.8/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.4ms)
  Rendered /usr/local/lib/ruby/gems/2.1.0/gems/actionpack-    
4.1.8/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.3ms)
 Rendered /usr/local/lib/ruby/gems/2.1.0/gems/actionpack-
4.1.8/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.9ms)
 Rendered /usr/local/lib/ruby/gems/2.1.0/gems/actionpack-
4.1.8/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout     
(30.2ms)

这是我的控制器中产生此输出的方法:

def index
  #This is the default call and should list all tournaments.
  @tournaments = Tournament.all
  @tournaments = @tournaments.order("startdate DESC")

  respond_to do |format|
    format.json { render :json => @tournaments }
  end
end
如果有人可以帮助我解决我的问题,那会很棒。我已经检查过,我确信UTF-8编码随处可见。此外,如果我通过rails控制台检查,我发现CharacterÜ编码为名称:“\ xDC”

1 个答案:

答案 0 :(得分:2)

def create
            name = params[:name]
            description = params[:description]
            orga = params[:raidlead]
            startdate = params[:startdate]
            enddate = params[:enddate]

            puts description

            name.force_encoding("ISO-8859-1").encode("UTF-8")
            description.force_encoding("ISO-8859-1").encode("UTF-8")
            orga.force_encoding("ISO-8859-1").encode("UTF-8")

诀窍,所以在将数据保存到数据库之前格式化字段对我来说是个窍门。实现这一诀窍的方法是:

string.force_encoding("ISO-8859-1").encode("UTF-8")

感谢Prakash Murthy的暗示。