我正與一個Web API,讓我像琴絃工作如下:我收到一個格式不正確的Unicode中的String
"Eat pok\u00e9."
Xcode的抱怨
以Unicode後括號需要的十六進制代碼越獄
我的理解是,它應該轉換爲pok\u{00e9}
,但我不知道如何實現這一點。
任何人都可以指出我在正確的方向爲我開發一種轉換這些方式,因爲有很多在這個API?
獎勵: 我還需要從字符串中刪除\n
。
我正與一個Web API,讓我像琴絃工作如下:我收到一個格式不正確的Unicode中的String
"Eat pok\u00e9."
Xcode的抱怨
以Unicode後括號需要的十六進制代碼越獄
我的理解是,它應該轉換爲pok\u{00e9}
,但我不知道如何實現這一點。
任何人都可以指出我在正確的方向爲我開發一種轉換這些方式,因爲有很多在這個API?
獎勵: 我還需要從字符串中刪除\n
。
您可能想給我們更多關於原始服務器有效負載看起來像什麼樣的背景,並向我們展示如何顯示字符串。在調試器中檢查字符串的一些方法(或者如果您正在查看原始JSON)將顯示您轉義字符串,但是如果您在應用程序中使用該字符串,則會看到實際的Unicode字符。
我不知道你是否只是看着原始的JSON。 例如,我通過JSON,{"foo": "Eat pok\u00e9."}
下面的代碼:
let jsonString = String(data: data, encoding: NSUTF8StringEncoding)!
print(jsonString)
let dictionary = try! NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String: String]
print(dictionary["foo"]!)
它輸出:
{"foo": "Eat pok\u00e9."} Eat poké.
順便說一句,這個標準JSON轉義語法不應與斯威夫特的字符串字面困惑逸出的語法,其中,所述六角序列必須被包裹在括號:
print("Eat pok\u{00e9}.")
夫特使用不同的轉義語法在它們的字符串的文字,並且它不應與JSON等格式所使用的混淆。
\u{00e9}
是特定於Swift字符串文本的格式。當代碼被編譯時,這個符號被解析並轉換成它所代表的實際的Unicode標量。
您收到的是一種以特殊方式轉義Unicode標量的字符串。將這些逃脫的Unicode標量轉換爲它們代表的Unicode標量,看到這個answer.
@Rob爲服務器傳遞無效的Swift字符串提供了一個很好的解決方案。
如果您需要將「Eat pok \ u00e9。\ n」轉換爲Eat poké
,可以使用Swift 3 regex進行如下操作。
var input = "Eat pok\\u00e9.\n"
// removes newline
input = String(input.characters.map {
$0 == "\n" ? " " : $0
})
// regex helper function for sanity's sake
func regexGroup(for regex: String!, in text: String!) -> String {
do {
let regex = try RegularExpression(pattern: regex, options: [])
let nsString = NSString(string: text)
let results = regex.matches(in: text, options: [], range: NSMakeRange(0, nsString.length))
let group = nsString.substring(with: results[0].range)
return group
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return ""
}
}
let unicodeHexStr = regexGroup(for:"0\\w*", in: input)
let unicodeHex = Int(unicodeHexStr, radix: 16)!
let char = Character(UnicodeScalar(unicodeHex)!)
let replaced = input.stringByReplacingOccurrencesOfString("\\u"+unicodeHexStr, withString: String(char))
// prints "Eat poké"
print(replaced)
謝謝,這有助於我瞭解到底發生了什麼。我正在查看原始JSON,並不知道在將數據轉換爲字符串時它會被轉換。 –