How to convert a JSON string to a dictionary?

前端 未结 10 908
情深已故
情深已故 2020-11-22 05:57

I want to make one function in my swift project that converts String to Dictionary json format but I got one error:

Cannot convert expression\'s type

10条回答
  •  名媛妹妹
    2020-11-22 06:49

    I've updated Eric D's answer for Swift 5:

     func convertStringToDictionary(text: String) -> [String:AnyObject]? {
        if let data = text.data(using: .utf8) {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
                return json
            } catch {
                print("Something went wrong")
            }
        }
        return nil
    }
    

提交回复
热议问题