Deserialize JSON / NSDictionary to Swift objects

前端 未结 13 1507
情歌与酒
情歌与酒 2020-11-29 18:43

Is there a way to properly deserialize a JSON response to Swift objects resp. using DTOs as containers for fixed JSON APIs?

Something similar to http://james.newtonk

13条回答
  •  离开以前
    2020-11-29 18:58

    You do this by using NSJSONSerialization. Where data is your JSON.

    First wrap it in an if statement to provide some error handling capablity

    if let data = data,
     json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject] {
    // Do stuff
    } else {
      // Do stuff
      print("No Data :/")
    }
    

    then assign them:

    let email = json["email"] as? String
    let name = json["name"] as? String
    let password = json["password"] as? String
    

    Now, This will show you the result:

    print("Found User iname: \(name) with email: \(email) and pass \(password)")
    

    Taken from this Swift Parse JSON tutorial. You should check out the tutorial as it goes a lot more in depth and covers better error handling.

提交回复
热议问题