Correct handling of NSJSONSerialization (try catch) in Swift (2.0)?

后端 未结 3 1001
自闭症患者
自闭症患者 2020-12-01 12:24

arowmy init works fine in Swift < 2 but in Swift 2 I get a error message from Xcode Call can throw, but it is not marked with \'try\' and the error is not handled

相关标签:
3条回答
  • 2020-12-01 12:44

    The jsonObject can throw errors, so put it within do block, use try, and catch any errors thrown. In Swift 3:

    do {
        let anyObj = try JSONSerialization.jsonObject(with: data) as! [String: Any]
    
        let label = anyObj["label"] as! String
        let value = anyObj["value"] as! Int
        let uprate = anyObj["uprate"] as! Int
        let sufix = anyObj["sufix"] as! String
    
        let props = Fieldpropertie(label: label, value: value, uprate: uprate, sufix: sufix)
    
        // etc.
    } catch {
        print("json error: \(error.localizedDescription)")
    }
    

    Or, in Swift 4, you can simplify your code by making your struct conform to Codable:

    struct Fieldpropertie: Codable {
        let label: String
        let value: Int
        let uprate: Int
        let suffix: String
    }
    

    Then

    do {
        let props = try JSONDecoder().decode(Fieldpropertie.self, from: data)
        // use props here; no manual parsing the properties is needed
    } catch {
        print("json error: \(error.localizedDescription)")
    }
    

    For Swift 2, see previous revision of this answer.

    0 讨论(0)
  • 2020-12-01 12:47

    Don't know if it'll solve your problem, but isn't the method JSONObjectWithData:options:error:? I think you're missing the error parameter.

    0 讨论(0)
  • 2020-12-01 12:50

    JSONSerialization.JSONObject throws ErrorType and not NSError.

    so the correct catch is

    do {
        let anyObj = try JSONSerialization.JSONObject(with: data, options: []) as! [String:AnyObject]
        // use anyObj here
    } catch let error {
        print("json error: \(error)")
    }
    

    The type of error in catch let error is ErrorType

    0 讨论(0)
提交回复
热议问题