Swift及Swift 4中如何将字典的字符串表示转换为字典?
如何在Swift中将字典的字符串表示转换为字典?
通用解决方案(适配多数JSON格式字典字符串)
咱们平常见到的字典字符串基本都是JSON格式,所以用Swift自带的JSONSerialization就能搞定。核心逻辑是先把字符串转成Data,再解析成JSON对象,最后转成字典类型。这里必须加错误处理,毕竟不是所有字符串都是合法JSON对吧?
给你个简单示例:
let dictString = "{\"key\": \"value\", \"number\": 123}" do { // 第一步:把字符串转为Data guard let data = dictString.data(using: .utf8) else { throw NSError(domain: "转换失败", code: 0, userInfo: [NSLocalizedDescriptionKey: "无法将字符串转为Data"]) } // 第二步:解析JSON对象 let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) // 第三步:转成[String: Any]类型字典 if let dictionary = jsonObject as? [String: Any] { print(dictionary) // 这里就可以正常使用字典啦 } else { throw NSError(domain: "解析失败", code: 1, userInfo: [NSLocalizedDescriptionKey: "JSON对象不是字典类型"]) } } catch { print("出错啦:\(error.localizedDescription)") }
Swift 4环境下转换指定字符串为字典
你给出的字符串是标准JSON格式,除了上面的JSONSerialization,还可以用Swift 4新增的Codable协议——这种方式更类型安全,不用反复拆包Any类型,项目里用起来更省心。
方法1:用JSONSerialization(快速通用)
直接把你的字符串套进通用逻辑里就行,而且你的字典值全是字符串,还能直接转成[String: String]:
let yourString = "{\"cover_image\":\"CI\",\"profile_image\":\"PI\",\"github\":\"\",\"location\":\"Somewhere between the north pole and the south pole\",\"name\":\"R\",\"website\":\"mysitesucksyoudon'twannavisititrightnow.imforreal\",\"about\":\"Yeah, I'm a human.\"}" do { guard let data = yourString.data(using: .utf8) else { throw NSError(domain: "转换失败", code: 0, userInfo: nil) } if let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String: String] { print("封面图:\(dict["cover_image"] ?? "")") print("用户名:\(dict["name"] ?? "")") // 其他字段按需取用就行 } } catch { print("解析错误:\(error)") }
方法2:用Codable(类型安全首选)
先定义一个和JSON结构匹配的结构体,遵守Codable协议:
struct UserProfile: Codable { let coverImage: String let profileImage: String let github: String let location: String let name: String let website: String let about: String // JSON的下划线key和结构体驼峰属性映射 enum CodingKeys: String, CodingKey { case coverImage = "cover_image" case profileImage = "profile_image" case github, location, name, website, about } }
然后用JSONDecoder解析:
let yourString = "{\"cover_image\":\"CI\",\"profile_image\":\"PI\",\"github\":\"\",\"location\":\"Somewhere between the north pole and the south pole\",\"name\":\"R\",\"website\":\"mysitesucksyoudon'twannavisititrightnow.imforreal\",\"about\":\"Yeah, I'm a human.\"}" do { guard let data = yourString.data(using: .utf8) else { throw NSError(domain: "转换失败", code: 0, userInfo: nil) } let userProfile = try JSONDecoder().decode(UserProfile.self, from: data) // 直接用类型安全的属性,不用拆包 print("用户名称:\(userProfile.name)") print("用户位置:\(userProfile.location)") print("个人简介:\(userProfile.about)") } catch { print("解析错误:\(error)") }
这种方式的好处是,编译器会帮你检查字段是否匹配,不用处理Any类型的不确定性,运行时出错概率更低。
内容的提问来源于stack exchange,提问作者Rishi556
相关产品推荐
相关产品推荐

