如果我将以下内容作为 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/