【问题标题】:Convert a String representation of a Dictionary to a dictionary in Swift?将字典的字符串表示形式转换为 Swift 中的字典?
【发布时间】:2018-04-13 23:40:09
【问题描述】:

如果我有以下String,如何在 Swift 4 中将其转换为 Dictionary?

{"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."}

【问题讨论】:

    标签: swift string swift4


    【解决方案1】:

    你可以使用JSONSerialisation方法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"]
    

    【讨论】:

    • 我建议改用 Codable
    猜你喜欢
    • 2010-11-02
    • 2021-12-01
    • 1970-01-01
    • 2011-05-06
    • 2019-12-05
    • 1970-01-01
    相关资源
    最近更新 更多