swift 将字典解码为不带反斜杠的字符串“\”

xytpbqjk  于 2023-05-28  发布在  Swift
关注(0)|答案(2)|浏览(176)

我有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)

那么我怎样才能得到一个没有多余字符“干净”的字符串呢?

gj3fmq9x

gj3fmq9x1#

import Foundation

func prettyPrintJSON(_ jsonString: String) {
    guard let jsonData = jsonString.data(using: .utf8) else {
        print("Invalid JSON string")
        return
    }
    
    do {
        let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: [])
        
        if let prettyPrintedData = try? JSONSerialization.data(withJSONObject: jsonObject, options: [.prettyPrinted]),
           let prettyPrintedString = String(data: prettyPrintedData, encoding: .utf8) {
            print(prettyPrintedString)
        } else {
            print("Failed to pretty print JSON")
        }
    } catch {
        print("Error parsing JSON: \(error)")
    }
}

// Example usage
let jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"
prettyPrintJSON(jsonString)

这将打印:

{
  "name" : "John",
  "age" : 30,
  "city" : "New York"
}
lyr7nygr

lyr7nygr2#

你可以在字典上使用一个扩展,它以一种漂亮的打印格式返回字符串。参见扩展名:

extension Dictionary {
      func jsonFormat() -> String {
        var theString = ""
        if let theJSONData = try?  JSONSerialization.data(
            withJSONObject: self,
            options: .prettyPrinted
        ),
        let theJSONText = String(data: theJSONData,
                                    encoding: String.Encoding.ascii) {
            theString = theJSONText
        }
        return theString
      }
   }

要使用它,您只需在字典上调用.jsonFormat,如下所示:

let tokenDict = ["paymentData" : paymentDataDict, "paymentMethod" : methodDict, "transactionIdentifier" : transactionIdentifierApplePay] as [String : Any]

let stringFormatDictionary = tokenDict.jsonFormat()
print(stringFormatDictionary)

打印:

{
  "transactionIdentifier" : "transactionIdentifierApplePay",
  "paymentData" : "paymentDataDict",
  "paymentMethod" : "methodDict"
}

这是一个字符串

相关问题