Swift - Create data model from JSON response

后端 未结 6 1980
小鲜肉
小鲜肉 2021-02-02 01:08

I\'m learning Swift lang and one of the things that would be great to hear others input about is \"How you handle models from JSON responses\"? For example -

I have

6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 01:43

    Here is some example code for Model Class and parsing JSON response with out any library.

    Model Class

    class User: NSObject{
         var user_token: String = ""
         var email: String = ""
    }
    

    Example code to call web-service api and Parsing.

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
                    var err: NSError
                    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
                    //println("Result : \(jsonResult)")
                    let model = User()
                model. user_token = jsonResult["user_token"] as NSString
                model. email = jsonResult["email"] as NSString
                })
    

提交回复
热议问题