swift - 将字典的字符串表示形式转换为 Swift 中的字典?

标签 swift string swift4

如果我将以下内容作为 String,如何在 Swift 4 中将其转换为 Dictionary

{"cover_image":"CI","profile_image":"PI","github":"","location":"北极和南极之间的某处","name": "R","website":"mysitesucksyoudon'twannavisititrightnow.imforreal","about":"是的,我是人。"

最佳答案

您可以使用 JSONSerialization 方法 class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any:

let str = """
{"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."}
"""
let dict = (try? JSONSerialization.jsonObject(with: Data(str.utf8))) as? [String:String] ?? [:]

print(dict)  // ["name": "R", "location": "Somewhere between the north pole and the south pole", "website": "mysitesucksyoudon\'twannavisititrightnow.imforreal", "github": "", "cover_image": "CI", "about": "Yeah, I\'m a human.", "profile_image": "PI"]

关于swift - 将字典的字符串表示形式转换为 Swift 中的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49826453/

相关文章:

ios - 我可以更改颜色/图像 UISearchBar 清除按钮吗?

swift - 当 ElementOfResult 被推断为 Optional 时,flatMap 不会过滤掉 nil

ios - keyboardFrameEndUserInfoKey 没有显示正确的值?

ios - 如何将属性值 UIScrollView.content.contentInsetAdjustmentBehavior 从 AppDelegate 更改为从不?

c# - 在 C# 中验证一个字符串是否只包含字母

python - 使用模式在 python 中版本字符串

c - 将文件路径拆分为路径和文件的函数

ios - 当我在 uipageviewcontroller 上调用 self.view.removeFromSuperview() 时,出现黑屏

json - 使用按钮更新用户位置并快速绘制路线

swift - NSCollectionView,Swift 4 - 无法调用 "register"