swift无法使用转义序列解码字符串
我的字符串格式为 SO \/ME \/STR \/ING
.我想要模拟json进行测试.而当我创建具有以下格式的json时:
I have string on format SO\/ME\/STR\/ING
. And I want to have mock json for testing. And when I create json with format like:
let json = """
{ "str": "SO\/ME\/STR\/ING" } // Error: Invalid escape sequence in literal
"""
对于我写的代码,如 SO \\/ME \\/STR \\/ING
.但是它解码不正确:
For what I wrote it like SO\\/ME\\/STR\\/ING
. But it decodes incorrect:
let json = """
{
"str": "SO\\/ME\\/STR\\/ING",
}
"""
let jsonData = Data(json.utf8)
let decoder = JSONDecoder()
do {
let model = try decoder.decode(Model.self, from: jsonData)
print(model) // Model(str: "SO/ME/STR/ING")
} catch {
print(error.localizedDescription)
}
如何正确解码?
在swift字符串中需要4个反斜杠,以表示 model.str
中的实际反斜杠:
You need 4 backslashes in the swift string to represent an actual backslash in model.str
:
let json = """
{
"str": "\\\\",
}
"""
let jsonData = Data(json.utf8)
let decoder = JSONDecoder()
do {
let model = try decoder.decode(Model.self, from: jsonData)
print(model.str) // prints a single backslash
} catch {
print(error.localizedDescription)
}
JSON 字符串中的反斜杠需要转义,因此在JSON字符串中需要2个反斜杠,但是要在 Swift 字符串文本中编写反斜杠,则需要逃避这两个反斜杠.因此有4个反斜杠.
A backslash in a JSON string needs to be escaped, so you need 2 backslashes in the JSON string, but to write this in a Swift string literal, you need to escape those two backslashes too. Hence the 4 backslashes.