简体   繁体   中英

Extra slash ( \ ) getting added when string (with unicode character) added to a dictionary

I am facing the following issue:

In my app, the user can enter special characters (like emojis) in a textfield also. So, while sending this entered text to server in request body, I am converting it using the following code:

func emojiToUTF8()->String
    {
        let data = self.data(using: .nonLossyASCII, allowLossyConversion: true)
        let emoji = String.init(data: data!, encoding: .utf8)
                
        return emoji ?? self
    }

For instance, if I enter the text "☺️" , it gets converted into "\☺\️" using the above method. Things are fine till here.

The problem occurs when I add this to a dictionary for sending it as a request parameter to the server. Code i'm using:

var parameters = [String:String]()

parameters["feedback"] = feedBackTxt

print("Parameters:",parameters) /// output: ["feedback": "\\u263a\\ufe0f"]

So, the problem here is that an extra slash is getting appended before each slash due to char escaping. I checked the created dictionary value as well. It shows double slash there also. How do I avoid this? Why is this happening when I am simply creating a dictionary with a string? This is causing issue at server end.

I have tried a couple of things, but none of them seem to work.

Your problem is that you're double-encoding.

You're taking a string, converting it to ASCII, then re-parsing it as UTF8 and then encoding that (probably) as JSON, which is UTF8. In the process, the backslashes are being escaped by your second encoder.

The best solution to this is to rework your server to accept UTF8. However, if you can't do that, you need to ensure you encode this string just one time, in ASCII.

In short, you should get rid of emojiToUTF8 and ensure that your parameters processor encodes the way your server requires (which apparently is ASCII and not UTF8).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM