func objectToJSONString(dictionaryOrArray: Any) -> String? {
do {
//Convert to Data
let jsonData = try JSONSerialization.data(withJSONObject: dictionaryOrArray, options: JSONSerialization.WritingOptions.prettyPrinted)
//Convert back to string. Usually only do this for debugging
if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
return JSONString
}
} catch {
print(error.localizedDescription)
}
return nil
}
Выход будет
Изменить для точного ответа
Объявление расширения строки для строки
extension String {
var unescaped: String {
let entities = ["\0": "\\0",
"\t": "\\t",
"\n": "\\n",
"\r": "\\r",
"\"": "\\\"",
"\'": "\\'",
]
return entities
.reduce(self) { (string, entity) in
string.replacingOccurrences(of: entity.value, with: entity.key)
}
.replacingOccurrences(of: "\\\\(?!\\\\)", with: "", options: .regularExpression)
.replacingOccurrences(of: "\\\\", with: "\\")
}
}
Модифицированный код будет
let array = ["1","2","3","4","5"]
let jsonString = objectToJSONString(dictionaryOrArray: array)
print(jsonString!.debugDescription) // this will print "[\"1\",\"2\",\"3\",\"4\",\"5\"]"
let result = jsonString!.debugDescription.unescaped
print(result)
Итак, вывод
Happy Coding:)