【问题标题】:Encoding 4 byte UTF-8 character ???? to JSON from Rails produce invalid character编码 4 字节 UTF-8 字符 ????从 Rails 到 JSON 产生无效字符
【发布时间】:2014-08-07 02:57:10
【问题描述】:

我在 Rails (3.2.19) 中有一个 Web 服务,它对 JSON 进行编码以供某些 iOS 或 Android 应用程序读取。 json 可能包含任何字符,但每次我使用 4 字节 UTF8 字符(例如 ????)时它似乎都会失败:它会生成 \uf4a9 aka

在 Rails 控制台中,字符正确显示,但是当我在 iOS 中使用 AFNetworking 或 HTTParty 检索答案时,它失败了。

这是我检索错误 JSON 的代码示例:

puts HTTParty.post( 'http://0.0.0.0:3000/login',
:body => { :login => 'antoine',
           :password => 'thisisnotmypassword',
         }.to_json,
:headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json' })

对 JSON 进行编码:

format.json { render json: json_reponse } #json_response is a Hash.

发送其他 UTF-8 字符效果很好,例如:ضصيتحضصتحخـ

【问题讨论】:

    标签: ruby-on-rails json utf-8 afnetworking httparty


    【解决方案1】:

    您的 Web 服务对 JSON 的编码不正确。看起来您没有使用标准 JSON 编码器,因为 as of Rails 3.2.13, the Unicode characters are passed through(也就是说,您不应该看到 any \u1234-type 编码。)

    也就是说,如果您想保持旧的编码,请尝试从 object.to_json 切换到 JSON.generate(object, :ascii_only => true).(更多详细信息请参见第 1 段的链接。)

    【讨论】:

      【解决方案2】:

      最后我用了

      JSON::dump(obj))

      【讨论】:

        【解决方案3】:

        Oj 也能胜任:

        Oj.dump(obj, mode: :compat)
        

        您必须将 oj 添加到您的宝石列表中

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-05-11
          • 2011-07-25
          • 1970-01-01
          • 2012-01-20
          • 2014-03-17
          • 1970-01-01
          • 1970-01-01
          • 2012-09-22
          相关资源
          最近更新 更多