ios 表情符号字符无法编码为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7177808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:15:07  来源:igfitidea点击:

Emoji characters cannot be encoded to JSON

iosjsoncharacter-encodingemoji

提问by janusfidel

I have a UITextViewwhich I call messageField. The data within that messageFieldis POST-ed to server in JSON format. When the user types an Emoji character I am having trouble encoding the data to JSON. I am thinking Emoji uses Unicode encoding.

我有一个UITextView我称之为messageField. 内的数据messageFieldPOST-ed服务器JSON格式。当用户键入表情符号字符时,我无法将数据编码为JSON. 我在想表情符号使用 Unicode 编码。

Is there a way to encode an Emoji character to JSON? And back from JSON to Emoji to display in a UILabel?

有没有办法将表情符号字符编码为 JSON?然后从 JSON 返回到 Emoji 以显示在UILabel?

采纳答案by Chris Haas

Edit - 2016-03-03Please note, this answer was written in 2011 and may no longer be relevant any more.

编辑 - 2016-03-03请注意,这个答案写于 2011 年,可能不再相关。

Emoji characters are just a specific font used to render specific unicode code points. iOS uses one of the Unicode Private Use Areas for Emoji-specific code points. The only way to view these "characters" as Emoji is to have an Emoji font available as well as a machine that knows how to switch from the default text font (such as Helvetica) to the emoji font.

表情符号字符只是用于呈现特定 unicode 代码点的特定字体。iOS 使用 Unicode 专用区域之一作为表情符号特定的代码点。将这些“字符”视为表情符号的唯一方法是拥有可用的表情符号字体以及知道如何从默认文本字体(例如 Helvetica)切换到表情符号字体的机器。

I don't know how you're encoding your JSON but since Emoji are just text there shouldn't be any problems as long as you transport the text in a Unicode-friendly format such as UTF-8 or UTF-16. You won't see it on the server-side or in the database (unless you view the data with the previous prerequisites) but you should be able to send the same raw bytes back and it should look the same.

我不知道您是如何编码 JSON 的,但由于表情符号只是文本,因此只要您以 Unicode 友好格式(例如 UTF-8 或 UTF-16)传输文本,就不会有任何问题。您不会在服务器端或数据库中看到它(除非您查看具有先前先决条件的数据),但您应该能够发回相同的原始字节,并且看起来应该相同。

Here's some posts that might help a little more:

以下是一些可能会有所帮助的帖子:

回答by Karun

I use the below code to encode emoji character

我使用以下代码对表情符号字符进行编码

NSString *uniText = [NSString stringWithUTF8String:[textview.text UTF8String]]; 
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding]; 
NSString *goodMsg = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding] ;

And the below code to decode and display in UILabel

和下面的代码解码和显示在 UILabel

const char *jsonString = [body UTF8String]; 
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)]; 
NSString *goodMsg = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];

回答by Lito

Thanks @Karu, editing your response,I use this code:

谢谢@Karu,编辑您的回复,我使用以下代码:

Encode for send to server:

发送到服务器的编码:

NSString *uniText = [NSString stringWithUTF8String:[text_to_send UTF8String]];

NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];

NSString *str = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];

Decode to receive and showing emoji text:

解码以接收和显示表情符号文本:

NSData *newdata = [received_string dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

NSString *mystring = [[NSString alloc] initWithData:newdata encoding:NSNonLossyASCIIStringEncoding];

NSString *finalString= @"";

if (mystring) {
   finalString = mystring;
}else{
   finalString = received_string;
}

This code run perfect on iOS 9

此代码在 iOS 9 上运行完美

回答by lionel

I had the same problem, after digging for hours and finally found this answer that works for me: https://stackoverflow.com/a/8339255/1090945

我遇到了同样的问题,经过几个小时的挖掘,终于找到了对我有用的答案:https: //stackoverflow.com/a/8339255/1090945

If you are using rails as your server, this is all you need to do. No need to do anything in ios/xcode, just pass the NSString without doing any UTF8/16 encoding stuff to the server.

如果您使用 rails 作为您的服务器,这就是您需要做的全部。无需在 ios/xcode 中执行任何操作,只需将 NSString 传递给服务器,而无需执行任何 UTF8/16 编码。

Postegre stores the code correctly, it's just when you send the json response back to your ios client, assuming you do render json:@message, the json encoding has problem.

Postegre 正确存储代码,只是当您将 json 响应发送回您的 ios 客户端时,假设您确实渲染了 json:@message,则 json 编码有问题。

you could test whether you are having json encoding problem in your rails console by doing as simple test:

您可以通过执行简单的测试来测试您的 rails 控制台中是否存在 json 编码问题:

test = {"smiley"=>"u{1f604}"} test.to_json

test = {"smiley"=>"u{1f604}"} test.to_json

if it prints out "{\"smiley\":\"\uf604\"}" (notice the 1 is lost), then you have this problem. and the patch from the link will fix it.

如果它打印出 "{\"smiley\":\"\uf604\"}" (注意 1 丢失了),那么你有这个问题。来自链接的补丁将修复它。

回答by Chathuranga Silva

Update Swift & Objective C

更新 Swift 和 Objective C

If you want to send send an emoji item through JSON, first you need to formate DB to UTF-8 AND in IOS you need to encode for NSUTF8StringEncoding. So first make sure your DB formate to UTF-8 then encode parameters to NSUTF8StringEncoding.So here is a sample request when sending the message.

如果您想通过 JSON 发送表情符号项,首先您需要将 DB 格式化为 UTF-8,并且在 IOS 中您需要编码为 NSUTF8StringEncoding。所以首先确保你的数据库格式为 UTF-8,然后将参数编码为 NSUTF8StringEncoding.So 这里是发送消息时的示例请求。

    let post:NSString = parameters!
    let url:NSURL = NSURL(string: serverURL!)!
    let postData:NSData = post.dataUsingEncoding(NSUTF8StringEncoding)! // Change Here
    let postLength:NSString = String( postData.length )
    let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.HTTPBody = postData
    request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("*/*", forHTTPHeaderField: "Accept")
    return request

But you don't need to decode to NSUTF8StringEncoding in iOS.Because according to the apple documentation it decode 5 encodings.

但是你不需要在 iOS 中解码为 NSUTF8StringEncoding。因为根据苹果文档它解码了 5 种编码。

The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/#//apple_ref/occ/clm/NSJSONSerialization/JSONObjectWithData:options:error:

数据必须采用 JSON 规范中列出的 5 种受支持编码之一:UTF-8、UTF-16LE、UTF-16BE、UTF-32LE、UTF-32BE。数据可能有也可能没有 BOM。用于解析的最有效编码是 UTF-8,因此如果您可以选择对传递给此方法的数据进行编码,请使用 UTF-8。

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/#//apple_ref/occ/clm/NSJSONSerialization/JSONObjectWithData:options:error

回答by Richard

One thing to be aware of with Emoji - if your json encoder is set to produce ASCII output (i.e. using the \u<4 hex digits> character format), some Emoji characters will break because they use more than two bytes and thus don't fit in the 4 hex digits allowed.

使用 Emoji 需要注意的一件事 - 如果您的 json 编码器设置为生成 ASCII 输出(即使用 \u<4 hex digits> 字符格式),则某些 Emoji 字符会中断,因为它们使用两个以上的字节,因此不会“ t 适合允许的 4 个十六进制数字。

So in python for example, be sure to use:

所以以python为例,一定要使用:

json.dumps(<object containing emoji strings>, ensure_ascii=False)