1、準(zhǔn)備一個(gè).json的文件放入swift工程
banner.json
{
"banners": [
{
"imgUrl": "https://www.baidu.com/img/flexible/logo/pc/result@2.png",
"action": "www.baidu.com",
"actionInfo": {
"url": "https://www.baidu.com",
"tip": ""
}
},
{
"imgUrl": "https://www.baidu.com/img/flexible/logo/pc/result@2.png",
"action": "",
"actionInfo": {
"url": "https://www.baidu.com",
"tip": "提示"
}
},
{
"imgUrl": "https://www.baidu.com/img/flexible/logo/pc/result@2.png",
"action": "",
"actionInfo": {
"url": "https://www.baidu.com",
"tip": "提示"
}
}
]
}
2、創(chuàng)建mode繼承自Codable
BannerModel.swift
class BannerModel: Codable {
var banners: [Banner]?
class Banner: Codable {
var imgUrl: String = ""
var action: String = ""
var actionInfo: ActionInfo?
class ActionInfo: Codable {
var url: String?
var tip: String?
}
}
}
3、讀取.json文件并轉(zhuǎn)化為目標(biāo)model
{
guard let path = Bundle.main.path(forResource: "banner", ofType: "json") else { return }
let localData = NSData.init(contentsOfFile: path)! as Data
do {
// banner即為我們要轉(zhuǎn)化的目標(biāo)model
let banner = try JSONDecoder().decode(BannerModel.self, from: localData)
if let banners = banner.banners {
self.banners = banners
}
} catch {
debugPrint("banner===ERROR")
}
}