下面的代码,我用来将字符串
转换为字典
,但不起作用。
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/