ios - 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.
解决方案
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"]
推荐阅读
- ios - FrontBoardServices - [FBSSceneParameters initWithSpecification:]:使用 CarPlay 时崩溃
- go - 使用 Golang 从给定点生成特定半径内的随机地理位置
- python-3.x - 向 gdal.Translate() 添加进度条
- mariadb - MariaDB 列存储数据 cpimport 中的“打开列文件时出错”
- android - 从不同的小部件禁用 PageView 物理
- google-cloud-platform - Google Cloud Identity API - 缺少设备字段/数据
- node.js - 通过nodejs对mongo进行join查询
- javascript - 当使用 React 钩子 useEffect() 更改对象数组时重新渲染
- extjs - 如何在编辑器网格面板内呈现远程组合框的初始显示值?
- django - 检测模型是否是 M2M 关系的直通模型