用引号打印黑色斜线

时间:2016-11-16 10:48:42

标签: ios swift nsstring printf

打印变量

var vin = "{\"method\": \"vinotestMethod\"}"
print(vin)

给我输出:

  

{“method”:“vinotestMethod”}

但我需要输出如:

  

{\“method \”:\“vinotestMethod \”}

我们怎么能在Swift中做到?

2 个答案:

答案 0 :(得分:1)

要逃避反斜杠,请将其加倍:

ByteOrder.nativeOrder()

将打印:

  

{\“method \”:\“vinotestMethod \”}

答案 1 :(得分:1)

如果您想创建JSON,那么您需要使用\来代替自己使用JSONSerialization进行撰写。

Swift 3

let dic = ["method" : "vinotestMethod"] //Add other key-value pair that you want
if let data = try? JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted) {
    let str = String(data: data, encoding: .utf8)
    print(str)
    //If you doesn't want `\n` with String
    print(str?.replacingOccurrences(of: "\n", with: ""))
}

Swift 2.3或更低

let dic = ["method" : "vinotestMethod"] //Add other key-value pair that you want
if let data = try? NSJSONSerialization.dataWithJSONObject(dic, options: .PrettyPrinted) {
    let str = String(data: data, encoding: NSUTF8StringEncoding)
    print(str)
    //If you doesn't want `\n` with String
    print(str?.stringByReplacingOccurrencesOfString("\n", withString: ""))
}