// 注意:解析时json与模型属性个数可以不匹配,但类型必须匹配
struct Respone: Codable {
let code: Int?
let message: String?
let data: TokenData?
}
struct TokenData: Codable {
let accessToken: String?
let type: String?
let expiresAt: Int?
// 注意:json的key和模型属性不同时,可以使用映射
enum CodingKeys: String, CodingKey {
case accessToken = "access_token"
case type
case expiresAt = "expires_at"
}
}
// MARK: - Net
private func loadData() {
// 注意:swift要求集合包含不同类型的值时要显式指定参数类型。
let parameters: [String : Any] = ["brand":"Apple", "channel":1, "device_id":"123431472xvwerbxcvbvxc", "oaid":"", "os":"17.5.2", "device_mode":"iPhone X"]
// Foundation 对象转 json data
let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
let url = URL(string: "https://xxx.xxx.com/api/auth/login/guest")!
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig);
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
request.timeoutInterval = 5
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
print("出错了")
return
}
guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
print("请求出错了")
return
}
if let mimeType = httpResponse.mimeType, mimeType == "application/json" {
print("响应json类型")
if let data = data {
print("data = \(String(describing: String(data: data, encoding:.utf8)))")
let decoder = JSONDecoder()
// jsonData 转 模型
if let resp = try? decoder.decode(Respone.self, from: data) {
print("resp.code = \(String(describing: resp.code))")
print("resp.message = \(String(describing: resp.message))")
print("resp.accessToken = \(String(describing: resp.data?.accessToken))")
print("resp.type = \(String(describing: resp.data?.type))")
print("resp.expiresAt = \(String(describing: resp.data?.expiresAt))")
}
// 或 jsonData 转 Foundation 对象(即基础数据类型Dictionary, Array等,非自定义类)
let jsonObj = try? JSONSerialization.jsonObject(with: data)
print("jsonObj = \(String(describing: jsonObj))")
if let dict = jsonObj as? Dictionary<String, Any?> {
print("code = \(String(describing: dict["code"]))")
}
} else {
print("data 无数据")
}
} else {
print("响应其他类型")
}
}
task.resume()
}
private func loadData1() {
let url = URL(string: "https://whatsdual.tools-global.com/api/auth/login/guest")!
let sessionConfig = URLSessionConfiguration.default
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("出错了")
return
}
guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
print("请求出错了")
return
}
if let mimeType = httpResponse.mimeType, mimeType == "application/json" {
print("响应json类型")
if let data = data {
print("data = \(String(describing: String(data: data, encoding:.utf8)))")
let decoder = JSONDecoder()
if let resp = try? decoder.decode(Respone.self, from: data) {
print("resp.code = \(String(describing: resp.code))")
print("resp.message = \(String(describing: resp.message))")
print("resp.data = \(String(describing: resp.data))")
}
} else {
print("data 无数据")
}
} else {
print("响应其他类型")
}
}
task.resume()
}
Swift 网络请求与数据解析(JSON与模型互转)
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 手机的优势是携带方便,可以随时打开,而且手机通常总是处于联网状态的,所以网络支持对于手机很重要。而且Java的网络...
- 1.get请求: 2.post请求: 3.上传图片到服务 4.创建实体类class BaseModel: Hand...
- 分别是: Alamofire :swift版本的网络请求sdk,是AFNetworking研发团队研发的swif...
- 常用场景: 将网络请求Json数据、NSDictionary、数组,映射为数据模型。 将数据模型对象序列化成字典保...
- github地址:https://github.com/Gong-Shijie/network.git OkHtt...