0
我與SWIFT的Progrmamming初學者,我需要從JSON值它看起來像這樣:斯威夫特JSON解析Wunderground
{
"response": {
"version":"0.1",
"termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"astronomy": 1
}
}
, "moon_phase": {
"percentIlluminated":"23",
"ageOfMoon":"5",
"phaseofMoon":"Erstes Viertel",
"hemisphere":"North",
"current_time": {
"hour":"8",
"minute":"28"
},
"sunrise": {
"hour":"6",
"minute":"55"
},
"sunset": {
"hour":"19",
"minute":"50"
},
"moonrise": {
"hour":"9",
"minute":"50"
},
"moonset": {
"hour":"0",
"minute":"06"
}
},
"sun_phase": {
"sunrise": {
"hour":"6",
"minute":"55"
},
"sunset": {
"hour":"19",
"minute":"50"
}
}
}
我會從日落和日出到一個變量得到小時&分鐘!
我的代碼:
var sunriseHour: [String] = []
var sunriseMinute: [String] = []
var sunsetHour: [String] = []
var sunsetMinute: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
let url=URL(string:"http://api.wunderground.com/api/dbd539bd631e/astronomy/lang:DL/q/DL/iphofen.json")
do {
let allData = try Data(contentsOf: url!)
let data = try JSONSerialization.jsonObject(with: allData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
if let arrJSON = data["moon_phase"] {
if let sunriseData = arrJSON["sunrise"]{
print(sunriseData)
}
if let sunsetData = arrJSON["sunset"]{
print(sunsetData)
}
}
print("hour: ",sunriseHour)
print("minute: ",sunriseMinute)
print("hour: ",sunsetHour)
print("minute: ",sunsetMinute)
}
catch {
}
}
i相打印(sunriseData)和印刷(sunsetData)從此正確的數據得到:
可選({ 小時= 6; 分鐘= 55 ;})可選(小時= 19; 分鐘= 50;})小時:[]分鐘:[]小時:[]分鐘:[]
我如何得到它在變量sunriseHour,sunriseMinute,sunsetHour,sunsetMinute ..
謝謝你的幫助..!
你是我的英雄...... :-)謝謝 – Heisenberg