两个问题:
- 该值为
Int
,因此强制转换为[String:String]
的类型。
- JSON格式要求密钥用双引号引起来。
这适用于any
值类型
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: Any] {
let data = Data(text.utf8)
return try JSONSerialization.jsonObject(with: data) as? [String:Any] ?? [:]
}
,
我建议您使用Codable
协议。而不是使用字典,而是使用某些特定的类/结构将数据解析为其中的内容。您可以使用与此类似的代码:
struct Status: Codable {
let status: Int
}
let body = "{\"status\":0}".data(using: .utf8)!
do {
let decoder = JSONDecoder()
let status = try decoder.decode(Status.self,from: body)
print(status) //Status(status: 0)
} catch {
print("\(error)")
}
这是处理JSON响应的更安全的方法。此外,它还为您提供了有关发生问题的信息,因此您可以轻松地进行修复。例如,如果您使用let status: String
,则会出现此错误:
typeMismatch(Swift.String,Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "status",intValue: nil)],debugDescription: "Expected to decode String but found a number instead.",underlyingError: nil))
有关Codable
的更多信息,您可以在Apple撰写的Encoding and Decoding Custom Types文章中阅读,或者在线搜索Codable
教程-关于它的很多好文章。
,
let body = "{\"status\":\"0\"}"
do {
let dictionary = try convertToDictionary(from: body )
print(dictionary)
} catch {
print(error)
}
func convertToDictionary(from text: String) throws -> [String: Any] {
if let data = text.data(using: .utf8) {
do {
return try (JSONSerialization.jsonObject(with: data,options: []) as? [String: Any] ?? [:])
} catch {
print(error.localizedDescription)
}
}
return [:]
}
输出-> [“状态”:0]
,
由于输入的字符串不是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
}
本文链接:https://www.f2er.com/3167424.html