我有string:
"{\"paymentData\":{\"data\":\"xxxxxxxx\",\"signature\":\"xxxxxxxxx\",\"header\":{\"publicKeyHash\":\"xxxxxx\",\"ephemeralPublicKey\":\"xxxxxxxx\"},\"version\":\"xxxxx\"},\"paymentMethod\":{\"displayName\":\"xxxxx\",\"network\":\"xxxxxx\",\"type\":\"xxxxx\"},\"transactionIdentifier\":\"xxxxxxx\"}\n"
但我需要这一行没有反斜杠。我需要这样的东西:
{"paymentData":{"data":"xxxxxxx","signature":"xxxxxx","header":{"publicKeyHash":"xxxxx","ephemeralPublicKey":"xxxxx","transactionId":"xxxxx"},"version":"xxxxx"},"paymentMethod":{"displayName":"xxxx","network":"xxxx","type":"xxxx"},"transactionIdentifier":"xxxxx"}
我看到,在类似的问题在这里说,这些反斜杠将不会被传输。但是我需要用这一行在md5中做一个散列,这些反斜杠被考虑在内。如何摆脱它们?
我试着去做:
let newStr = tokenStr.replacingOccurrences(of: "\\", with: "")
或者它:
let string2 = string1.tokenStr.replacingOccurrences(#"\"#, with: "")
但不幸的是,那些反斜线依然存在
我的字符串看起来像这样:
let tokenStr = """
{"paymentData":{"data":"\(tokenApplePay.paymentData.data)","signature":"\(tokenApplePay.paymentData.signature)","header":{"publicKeyHash":"\(tokenApplePay.paymentData.header.publicKeyHash)","ephemeralPublicKey":"\(tokenApplePay.paymentData.header.ephemeralPublicKey)","transactionId":"\(tokenApplePay.paymentData.header.transactionId)"},"version":"\(tokenApplePay.paymentData.version)"},"paymentMethod":{"displayName":"\(tokenApplePay.paymentMethod.displayName)","network":"\(tokenApplePay.paymentMethod.network)","type":"\(tokenApplePay.paymentMethod.type)"},"transactionIdentifier":"\(tokenApplePay.transactionIdentifier)"}
"""
如果我将这些数据转换成数据,并解码成模型-那么我在每行之前会得到更多的字符
let tokenDict = ["paymentData" : paymentDataDict, "paymentMethod" : methodDict, "transactionIdentifier" : transactionIdentifierApplePay] as [String : Any]
let tokenData = try JSONSerialization.data(withJSONObject: tokenDict, options: [])
let tokenApplePay = try jsonDecoder.decode(PaymentDataContainer.self, from: tokenData)
debugPrint(tokenApplePay)
那么我怎样才能得到一个没有多余字符“干净”的字符串呢?
2条答案
按热度按时间gj3fmq9x1#
这将打印:
lyr7nygr2#
你可以在字典上使用一个扩展,它以一种漂亮的打印格式返回字符串。参见扩展名:
要使用它,您只需在字典上调用.jsonFormat,如下所示:
打印:
这是一个字符串