美文网首页
Swift:网络数据的解析和模型的创建

Swift:网络数据的解析和模型的创建

作者: xieyinghao | 来源:发表于2018-12-13 17:05 被阅读19次

    demo:https://gitee.com/xieyinghao/Swift_ModelDemo.git

    
     func loadDataByAFN() {
            NetworkTools.POST(url: "http://app.u17.com/v3/appV3_3/ios/phone/rank/list", params: nil, success: { (json) in
                
                let newStr = String(data: json, encoding: String.Encoding.utf8)
    
                let dict = self.getDictionaryFromJSONString(jsonString: newStr!)
                
                print("\(dict)")
                
                或者:
                let decoder = JSONDecoder() //decoder 字符串转模型类
                let model = try? decoder.decode(DMModel.self, from: json)
                self.model = model
                self.tableView.reloadData()
    
    
    
            }) { (state_code, message) in
                
            }
        }
        
        func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{
            
            let jsonData:Data = jsonString.data(using: .utf8)!
            
            let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
            if dict != nil {
                return dict as! NSDictionary
            }
            return NSDictionary()
            
            
        }
    
    

    相关文章

      网友评论

          本文标题:Swift:网络数据的解析和模型的创建

          本文链接:https://www.haomeiwen.com/subject/ufubhqtx.html