从Rails将4字节UTF-8字符????编码为JSON会产生无效字符

时间:2022-02-04 00:18:48

I have a web service in rails (3.2.19) that encode a JSON to be read by some iOS or Android apps. The json might contain any characters, but it seems to fail every time I use a 4 bytes UTF8 character such as ????: it produce instead \uf4a9 aka .

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

In rails console the character is correctly displayed but when i retrieve the answer in iOS with AFNetworking or with HTTParty, it fails.

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

Here is my code sample to retrieve the faulty JSON:

这是我的代码示例,用于检索有故障的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' })

And to encode the JSON:

并编码JSON:

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

Sending other UTF-8 characters works well, for exemple: ضصيتحضصتحخـ

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

3 个解决方案

#1


4  

Your web service is encoding the JSON incorrectly. It looks like you're not using the standard JSON encoder, since as of Rails 3.2.13, the Unicode characters are passed through (that is, you shouldn't be seeing any \u1234-type encoding.)

您的Web服务正在错误地编码JSON。看起来你没有使用标准的JSON编码器,因为从Rails 3.2.13开始,Unicode字符会被传递(也就是说,你不应该看到任何\ u1234类型的编码。)

That said, if you want to maintain the old encoding, try switching from object.to_json to JSON.generate(object, :ascii_only => true). (More details in the link in the 1st paragraph.)

也就是说,如果要维护旧编码,请尝试从object.to_json切换到JSON.generate(object,:ascii_only => true)。 (第1段链接中的更多细节。)

#2


2  

In the end, I used

最后,我用了

JSON::dump(obj))

#3


0  

Oj can also do the job:

Oj也可以做这个工作:

Oj.dump(obj, mode: :compat)

You will have to add oj it to your gem list

你必须将它添加到你的宝石列表中

#1


4  

Your web service is encoding the JSON incorrectly. It looks like you're not using the standard JSON encoder, since as of Rails 3.2.13, the Unicode characters are passed through (that is, you shouldn't be seeing any \u1234-type encoding.)

您的Web服务正在错误地编码JSON。看起来你没有使用标准的JSON编码器,因为从Rails 3.2.13开始,Unicode字符会被传递(也就是说,你不应该看到任何\ u1234类型的编码。)

That said, if you want to maintain the old encoding, try switching from object.to_json to JSON.generate(object, :ascii_only => true). (More details in the link in the 1st paragraph.)

也就是说,如果要维护旧编码,请尝试从object.to_json切换到JSON.generate(object,:ascii_only => true)。 (第1段链接中的更多细节。)

#2


2  

In the end, I used

最后,我用了

JSON::dump(obj))

#3


0  

Oj can also do the job:

Oj也可以做这个工作:

Oj.dump(obj, mode: :compat)

You will have to add oj it to your gem list

你必须将它添加到你的宝石列表中