JSON String to NSDictionary with Swift

后端 未结 3 1609
孤城傲影
孤城傲影 2021-02-09 01:50

I am trying to create a dictionary from data that is held in a server, I receive the data but I cannot convert the data to an NSDictionary, I believe it is held in

相关标签:
3条回答
  • 2021-02-09 02:25

    Your code does not do any error handling. But it can (and if this data comes from a web service, will) fail in multiple ways.

    1. You have to make sure that your data object actually exists
    2. You have to make sure that the data object can be converted to JSON
    3. You have to make sure that the JSON actually contains a Dictionary

    You should use Swifts conditional cast and it's optional binding capabilities.
    The optional binding if let JSONData = JSONData checks that JSONData is not nil. The force unwrap (JSONData!) you use might crash if no data could be received.

    The optional binding if let json = NSJSONSerialization.JSONObjectWithData checks if the data could be converted to a JSON object. The conditional cast as? NSDictionary checks if the JSON object is actually a dictionary. You currently don't use these checks, you cast the objects as NSDictionary. Which will crash, if the object is not valid json, or if its not a dictionary.

    I would recommend something like this:

    var error: NSError?
    if let JSONData = JSONData { // Check 1
        if let json: AnyObject = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: &error) { // Check 2
            if let jsonDictionary = json as? NSDictionary { // Check 3
                println("Dictionary received")
            }
            else {
                if let jsonString = NSString(data: JSONData, encoding: NSUTF8StringEncoding) {
                    println("JSON String: \n\n \(jsonString)")
                }
                fatalError("JSON does not contain a dictionary \(json)")
            }
        }
        else {
            fatalError("Can't parse JSON \(error)")
        }
    }
    else {
        fatalError("JSONData is nil")
    }
    

    You could merge check 2 and 3 into one line and check if NSJSONSerialization can create a NSDictionary directly:

    var error: NSError?
    if let JSONData = JSONData { // Check 1.
        if let JSONDictionary = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: &error) as? NSDictionary { // Check 2. and 3.
            println("Dictionary received")
        }
        else {
    
            if let jsonString = NSString(data: JSONData, encoding: NSUTF8StringEncoding) {
                println("JSON: \n\n \(jsonString)")
            }
            fatalError("Can't parse JSON \(error)")
        }
    }
    else {
        fatalError("JSONData is nil")
    }
    

    Make sure to replace fatalError with appropriate error handling in your production code

    0 讨论(0)
  • 2021-02-09 02:41

    Here jsonResult will give you the response in NSDictionary:

    let url = NSURL(string: path)
            let session = NSURLSession.sharedSession()
            let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
                println("Task completed")
                if(error != nil) {
                    // If there is an error in the web request, print it to the console
                    println(error.localizedDescription)
                }
                var err: NSError?
                var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
                if(err != nil) {
                    // If there is an error parsing JSON, print it to the console
                    println("JSON Error \(err!.localizedDescription)")
                }
    
            })
            task.resume()
    
    0 讨论(0)
  • 2021-02-09 02:44

    Update for Swift 2.

    Now you must use it inside a try catch block.

        do {
            let responseObject = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String:AnyObject]
        } catch let error as NSError {
     print("error: \(error.localizedDescription)")
    }
    
    0 讨论(0)
提交回复
热议问题