2016-10-27 17 views
0

目標是通過將Swift對象轉換爲JSON對象,然後將JSON對象轉換爲JSON字符串,然後將其傳遞並解碼另一邊。Swift:如何抑制特殊字符的解釋並提供字符串文字

問題是生成有效的JSON字符串。

換行符必須在JSON字符串中轉義,但Swift將轉義轉義字符串中的特殊字符,而不是將字符串視爲文字。

例如:

let a = "foobar\nhello\nworld" 
let escapedString = a.replacingOccurrences(of: "\n", with: "\\n") 

print(escapedString) 

什麼獲取打印是foobar\nhello\nworld而不是所希望foobar\\nhello\\nworld

你如何看待Swift將字符串視爲文字而不解釋特殊字符?

UPDATE

作爲OOPer所指出的,使用debugPrint示出保持完整\\n字符。

然而,當與在evaluateJavaScriptWKWebView配對時,\\n字符變成\n,這是根問題。例如:

let script = "\(callback)(\'\(escapedString)\')"   
webView!.evaluateJavaScript(script) { (object: Any?, error: Error?) -> Void in 
    print("Done invoking \(callback)") 
} 

回答

1

在javascript模板文字中沒有非轉義字符串語法,這可能是您正在查找的內容;也許他們會在未來添加它。不幸的是,你必須逃避每個反斜槓,有時看起來很亂,就像你的例子。

//This is the same as `foobar\nhello\nworld` where each char is a literal 
    let a = "foobar\\nhello\\nworld" 
    let escapedString = a.replacingOccurrences(of: "\\n", with: "\\\\n") 
    //This outputs `foobar\\nhello\\nworld` 
    print(escapedString) 
0

也許你只是錯誤地解釋從print輸出。

當你從print(escapedString)foobar\nhello\nworldescapedString包含20個字符 - foobar\nhello\nworld

當在"之間包含時,這是一個有效的JSON字符串。

如果您要檢查在字符串字面般的符號逃脫的結果,你可以使用debugPrint

let a = "foobar\nhello\nworld" 
let escapedString = a.replacingOccurrences(of: "\n", with: "\\n") 

print(escapedString) //->foobar\nhello\nworld 
debugPrint(escapedString) //->"foobar\\nhello\\nworld" 

對於UPDATE

evaluateJavaScript使用,你」如果你想用JavaScript表示一個JSON轉義字符串,你可以用.js文件(或<script>...</script>)寫入:

someFunc('foobar\\nhello\\nworld'); 

所以,你可能需要編寫這樣的事:

let a = "foobar\nhello\nworld" 
let escapedForJSON = a.replacingOccurrences(of: "\n", with: "\\n") 
//In actual code, you may need a little more... 
let escapedForJavaScriptString = escapedForJSON.replacingOccurrences(of: "\\", with: "\\\\") 

let script = "\(callback)(\'\(escapedForJavaScriptString)\')" 
webView!.evaluateJavaScript(script) { (object: Any?, error: Error?) -> Void in 
    print("Done invoking \(callback)") 
} 
+0

這是一個很好的點,所以也許應該張貼更多的代碼,其中evaluateJavaScript.'的'內使用時的\\ n趨向走 – Crashalot

+0

更新的問題,會愛你的根源問題的反饋 – Crashalot