Swift: How to convert string to dictionary

2020-07-25 23:14发布

I have a dictionary which i convert to a string to store it in a database.

        var Dictionary =
    [
        "Example 1" :   "1",
        "Example 2" :   "2",
        "Example 3" :   "3"
    ]

And i use the

Dictionary.description

to get the string.

I can store this in a database perfectly but when i read it back, obviously its a string.

"[Example 2: 2, Example 3: 3, Example 1: 1]"    

I want to convert it back to i can assess it like

Dictionary["Example 2"]

How do i go about doing that?

Thanks

3条回答
手持菜刀,她持情操
2楼-- · 2020-07-25 23:55

I created a static function in a string helper class which you can then call.

 static func convertStringToDictionary(json: String) -> [String: AnyObject]? {
    if let data = json.dataUsingEncoding(NSUTF8StringEncoding) {
        var error: NSError?
        let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String: AnyObject]
        if let error = error {
            println(error)
        }
        return json
    }
    return nil
}

Then you can call it like this

if let dict = StringHelper.convertStringToDictionary(string) {
   //do something with dict
}
查看更多
啃猪蹄的小仙女
3楼-- · 2020-07-26 00:03

this is exactly what I am doing right now. Considering @gregheo saying "description.text is not guaranteed to be stable across SKD version" description.text could change in format-writing so its not very wise to rely on.

I believe this is the standard of doing it

    let data = your dictionary

    let thisJSON = try  NSJSONSerialization.dataWithJSONObject(data, options: .PrettyPrinted)

    let datastring:String = String(data: thisJSON, encoding: NSUTF8StringEncoding)!

you can save the datastring to coredata.

查看更多
狗以群分
4楼-- · 2020-07-26 00:08

What the description text is isn't guaranteed to be stable across SDK versions so I wouldn't rely on it.

Your best bet is to use JSON as the intermediate format with NSJSONSerialization. Convert from dictionary to JSON string and back.

查看更多
登录 后发表回答