首页 > 解决方案 > Find special characters entered in a textfield and escape in swift

问题描述

My requirement is to create a JSON from the text entered in a UITextField. There is no restriction to the UITextField. So, if a user enters a special character(", \ etc.), I want to escape the value entered and create a JSON.

String literals can include the following special characters:

  • The escaped special characters \0 (null character), \ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quote) and \' (single quote)
  • An arbitrary Unicode scalar, written as \u{n}, where n is a 1–8 digit hexadecimal number with a value equal to a valid Unicode code point

For example, if the user enters "Hello "User"! How to use a \ in a JSON?". It should return something like this "Hello \"User\"! How to use a \\ in a JSON?". Not just " or \, I would want to escape all the special characters.

Thanks! I truly appreciate your effort in providing me with a solution.

Edit I forgot to mention, this requirement is for Swift 4.2.

标签: iosswiftuitextfield

解决方案


Do not “manually” escape the characters in order to create JSON. There is a dedicated JSONEncoder() class for this purpose.

Top-level JSON objects can only be arrays or dictionaries. Here is an example for an array containing a single element with the given string:

let text = """
    Hello "User"! How to use a \\ in a JSON?
    Another line line
    """

do {
    let jsonData = try JSONEncoder().encode([text])
    let jsonString = String(data: jsonData, encoding: .utf8)!
    print(jsonString)
} catch {
    print(error.localizedDescription)
}

The output is

["Hello \"User\"! How to use a \\ in a JSON?\nAnother line"]

推荐阅读