Swift4新特性中,Codable协议真的能狂吸一波粉,个人不太喜欢SwiftyJSON这类的第三方库来解析数据,if let xxx = 方式也太繁琐了。
个人使用Alamofire库,封装自身项目网络框架,使用responseJSON返回JSON数据(或许有同学疑问,为什么不直接使用responseData返回data数据,个人觉得请求的某些数据没必要解析为模型,直接用就可以)
Alamofire.request(url, method: httpMethod, parameters: paramters, encoding: URLEncoding.default, headers: header).responseJSON
例子1: JSON数组
- 每个属性都需要可选类型(?)接收,否则,若没有该属性,解析失败;
- 每个属性的类型都需要准确,否则解析失败;
struct MajorDetailBasicFields: Codable {
var level2: String? // : 27,
var level1: String? // : 2,
var limit_year: String? // : 三年,
var special_id: String? // : 853,
var level2_name: String? // : 财经商贸大类,
var degree: String? // : ,
var view_week: String? // : 49,
var view_total: String? // : 20763,
var level3_name: String? // : 金融类,
var rank: String? // : 244,
var rankall: String? // : 167,
var sid: String? // : gkspecial853,
var level3: String? // : 194,
var level1_name: String? // : 专科,
var rank_type: String? // : 2,
var name: String? // : 金融管理,
var view_month: String? // : 65
}
struct MajorDetailBasic: Codable {
var model: String? // : gaokao.eolmajorlist,
var pk: String? // : 1d87f2c05f02c1b45de804be0f247524,
var fields: MajorDetailBasicFields? // : {
}
解析
guard let data = try? JSONSerialization.data(withJSONObject: result as Any, options: .prettyPrinted) else {
return
}
guard let list = try? JSONDecoder().decode([MajorDetailBasic].self, from: data) else {
return
}
至此,解析成功后,list中就是一个个MajorDetailBasic对象
例子2: JSON字典
依然是:
- 每个属性都需要可选类型(?)接收,否则,若没有该属性,解析失败;
- 每个属性的类型都需要准确,否则解析失败;
struct CollegeDetailInfo: Codable {
var site: String? // : http://zs.gzpyp.edu.cn,
var level_name: String? // :
var school_nature_name: String? // : 公办,
var address: String? //
var content: String? //
var phone: String? // : 020-34874086,020-84731206,
}
解析
guard let data = try? JSONSerialization.data(withJSONObject: result as Any, options: .prettyPrinted) else {
return
}
guard let info = try? JSONDecoder().decode(CollegeDetailInfo.self, from: data) else {
return
}
例子3: 自定义键值名
假如例子2中的属性phone我们想使用phoneNum表达,则该模型如下
struct CollegeDetailInfo: Codable {
var site: String? // : http://zs.gzpyp.edu.cn,
var level_name: String? // : 专科(高职),
var school_nature_name: String? // : 公办,
var address: String? //
var content: String? //
var phoneNum: String? // : 020-34874086,020-84731206,
///自定义键值名
enum CodingKeys: String, CodingKey {
case phoneNum = "phone"
case site
case level_name
case school_nature_name
case address
case content
}
}
PS: 虽然只是将phone->phoneNum 其他字符也需要在这里列一遍,否则转换失败
网友评论