gpt4 book ai didi

ruby-on-rails - Rails 使用 UTF-8 渲染 JSON 响应

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:50 24 4
gpt4 key购买 nike

我正在尝试使用 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)

这是我的 Controller 中产生此输出的方法:

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 控制台检查,我会看到字符 Ü 被编码为 name: "\xDC"

最佳答案

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 的提示。

关于ruby-on-rails - Rails 使用 UTF-8 渲染 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27796623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com