Swift:网络数据的解析和模型的创建
2018-12-13 本文已影响19人
xieyinghao
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()
}