How to convert a JSON string to a dictionary?

前端 未结 10 1020
情深已故
情深已故 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:38

    Warning: this is a convenience method to convert a JSON string to a dictionary if, for some reason, you have to work from a JSON string. But if you have the JSON data available, you should instead work with the data, without using a string at all.

    Swift 3

    func convertToDictionary(text: String) -> [String: Any]? {
        if let data = text.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            } catch {
                print(error.localizedDescription)
            }
        }
        return nil
    }
    
    let str = "{\"name\":\"James\"}"
    
    let dict = convertToDictionary(text: str)
    

    Swift 2

    func convertStringToDictionary(text: String) -> [String:AnyObject]? {
        if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
            do {
                return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
            } catch let error as NSError {
                print(error)
            }
        }
        return nil
    }
    
    let str = "{\"name\":\"James\"}"
    
    let result = convertStringToDictionary(str)
    

    Original Swift 1 answer:

    func convertStringToDictionary(text: String) -> [String:String]? {
        if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
            var error: NSError?
            let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:String]
            if error != nil {
                println(error)
            }
            return json
        }
        return nil
    }
    
    let str = "{\"name\":\"James\"}"
    
    let result = convertStringToDictionary(str) // ["name": "James"]
    
    if let name = result?["name"] { // The `?` is here because our `convertStringToDictionary` function returns an Optional
        println(name) // "James"
    }
    

    In your version, you didn't pass the proper parameters to NSJSONSerialization and forgot to cast the result. Also, it's better to check for the possible error. Last note: this works only if your value is a String. If it could be another type, it would be better to declare the dictionary conversion like this:

    let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]
    

    and of course you would also need to change the return type of the function:

    func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }
    

提交回复
热议问题