[英]Codable Swift JSON Parsing Nested JSON
我有看起來像這樣的 JSON 數據
{
"latitude": 34.088051,
"longitude": -118.296512,
"timezone": "America/Los_Angeles",
"daily": {
"summary": "No precipitation throughout the week, with high temperatures rising to 92°F on Friday.",
"icon": "clear-day",
"data": [
{
"time": 1535266800,
"summary": "Mostly cloudy in the morning.",
"icon": "partly-cloudy-day",
"sunriseTime": 1535289854,
"sunsetTime": 1535336915,
"moonPhase": 0.51}
我想從中提取時間,摘要,圖標。
我創建了一個 WeatherObject 類型的類,但這就是我卡住的地方。 如何創建結構? 鍵不是蛇形外殼或命名不當,所以我想我可以不使用枚舉來重命名變量名稱。
編輯:做 - 抓住跌倒。 VC 實現協議。 傳遞給協議方法的數據在方法實現中打印,但無法在 do 子句中處理。
protocol NetworkingDelegate: AnyObject {
func didGetResult(data: Data?) -> Void
}
class Networking: NSObject {
var data: Data?
weak var delegate: NetworkingDelegate?
func makeAPIRequest(apiString: String) -> Void {
guard let url: URL = URL(string: apiString) else{
print("ERROR no URL")
return
}
let urlRequest = URLRequest(url: url)
let dataSession = URLSession.shared
let dataTask = dataSession.dataTask(with: urlRequest) { (data, response, error) in
guard error == nil else{
print("ERROR found in networking call")
print(error!)
return
}
if data != nil{
print("Data exists in networking")
self.delegate?.didGetResult(data: data!)
}else{
print("ERROR: did not receive data")
}
}
dataTask.resume()
}
}
在視圖控制器中
func didGetResult(data: Data?) {
do {
if let dataObject = data{
let theString:NSString = NSString(data: dataObject, encoding: String.Encoding.ascii.rawValue)!
print(theString)
}
let newJSONDecoder = JSONDecoder()
let weatherObject = try newJSONDecoder.decode(WeatherObj.self, from:data!)
let dailyObject = weatherObject.daily
let dataArray = dailyObject.data
//LOOP THROUGH dataArray and get the required info
for val in dataArray {
print("=======")
print(val.time)
print(val.summary)
print(val.icon)
print("=======")
}
} catch {
print("error while parsing:\(error.localizedDescription)")
}
}
您可以像這樣創建結構
struct WeatherObject: Codable {
let latitude: Double
let longitude: Double
let timezone: String
let daily: Daily
}
struct Daily: Codable {
let summary: String
let icon: String
let data: [Datum]
}
struct Datum: Codable {
let time: Int
let summary: String
let icon: String
let sunriseTime: Int
let sunsetTime: Int
let moonPhase: Double
}
然后你可以解析它並獲得所需的信息
do {
let newJSONDecoder = JSONDecoder()
let weatherObject = try newJSONDecoder.decode(WeatherObject.self, from: jsonData)
let dailyObject = weatherObject.daily
let dataArray = dailyObject.data
//LOOP THROUGH dataArray and get the required info
for val in dataArray {
print("=======")
print(val.time)
print(val.summary)
print(val.icon)
print("=======")
}
} catch {
print("error while parsing:\(error.localizedDescription)")
}
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.