gpt4 book ai didi

swift - 如何将字符串转换为json字典?

转载 作者:行者123 更新时间:2023-11-30 10:33:03 24 4
gpt4 key购买 nike

下面的代码,我用来将字符串转换为字典,但不起作用。

let body = "{status:0}"
do {
let dictionary = try convertToDictionary(from: body ?? "")
print(dictionary) // prints: ["City": "Paris"]
} catch {
print(error)
}

func convertToDictionary(from text: String) throws -> [String: String] {
guard let data = text.data(using: .utf8) else { return [:] }

let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])

return anyResult as? [String: String] ?? [:]
}

最佳答案

由于输入字符串不是 json,我建议使用非 json 解决方案

let array = body.dropFirst().dropLast().split(separator: ":").map {String($0)} 

var dictionary = [String: String]()
if let key = array.first, let value = array.last {
dictionary[key] = value
}

关于swift - 如何将字符串转换为json字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58691836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com