Swift語言是一種強類型類型安全語言,它要求我們顯示的設置類型以減少代碼的bug。但是當Swift處理JSON這種數據時,就顯得非常麻煩,此時我們就可以考慮SwiftyJSON。
為什么用它?
例如我獲取一個這樣的JSON數據
{
"error_code" = 0;
reason = "\U6210\U529f";
result = (
{
CityName = "\U5b89\U5e86";
},
{
CityName = "\U868c\U57e0";
},
{
CityName = "\U5171\U548c";
}
);
}
我們需要這樣
if let resultDic = jsonValue as? NSDictionary {
if let resultArray = resultDic["result"] as? NSArray {
if let resultFirstDic = resultArray[0] as? NSDictionary{
if let resultFirstCity = resultFirstDic["CityName"] as? NSString{
print("\(resultFirstCity)")
}
}
}
}
上面這樣還是太麻煩了,但是我們有SwiftyJSON之后呢
let jsonWeNeedValue = JSON(data: jsonData)
if let firstCityName = jsonWeNeedValue["result"][0]["CityName"].string{
print("cityName ===\(firstCityName)")
}
當然它的優勢,不僅僅是這些,我們可以通過后期深入來了解其更多的好處。
初始化和基本使用
// 初始化
let json = JSON(data: dataFromNetworking)
//這里的object是AnyObject,但是必須是能轉會成JSON的數據類型。傳錯也沒關系,最多你后面再也取不到數據了。
let json = JSON(jsonObject)
// 然后就可以直接使用啦
//Getting a string using a path to the element
let path = [1,"list",2,"name"]
let name = json[path].string
//Just the same
let name = json[1]["list"][2]["name"].string
//Alternatively
let name = json[1,"list",2,"name"].string
具體還是看實際運用的咯
問題
1、它有哪些常用類型
jsonWeNeedValue["result"][0]["CityName"].string
jsonWeNeedValue["result"].array
jsonWeNeedValue.dictionary
基本我們用到的,它都有,而且還有stringValue
,后面提到。
2、注意可選和不可選
// 可選
if let firstCityName = jsonWeNeedValue["result"][0]["CityName"].string{
print("cityName ===\(firstCityName)")
}
else{
print("error == \(jsonWeNeedValue["result"][0]["CityName"])")
}
// 不可選
let secondCityName = jsonWeNeedValue[["result",1,"CityName"]].stringValue
print("secondCity ===\(secondCityName)")
也就是 string
和 stringValue
使用的不同,前者是Optional string
后者是 Non-optional string
,像后者假如不是string
或是nil
,它直接返回" "
也不會Cash。
3、快捷方式的輸入,如上面路徑[["result",1,"CityName"]]
和["result"][0]["CityName"]
是等同的
就等同于直接是獲取數據路徑一般,非常好用
let path =["result",1,"CityName"]
let name = jsonWeNeedValue[path].string
4、如果數組下標越界或者不存某個key呢
像上面我直接把路徑改為["result",10000,"CityName"]
,它也直接返回null
或空,反正不會Cash
,所以我們放心使用。
5、循環
循環字典:第一個參數是一個key, 第二個參數是JSON
let headers = ["apikey":"a566eb03378211f7dc9ff15ca78c2d93"]
Alamofire.request(.GET, "http://apis.baidu.com/heweather/pro/weather?city=beijing", headers: headers)
.responseJSON { response in
let jsonWeNeedData = JSON(data: response.data!)
// 字典
let cityDic = jsonWeNeedData["HeWeather data service 3.0",0,"aqi","city"].dictionaryValue
print("cityDic == \(cityDic)")
//cityDic == ["pm25": 11, "o3": 57, "qlty": 優, "aqi": 24, "co": 0, "so2": 5, "pm10": 18, "no2": 18]
for (key, sub) in cityDic {
if key == "pm25" {
print("subString == \(sub)")
// subString == 11
}
}
}
當然數組也是一樣,注意循環數組也只能用元組,第一個參數是一個string的index, 第二個參數是JSON
//If json is .Array
//The `index` is 0..<json.count's string value
for (index,subJson):(String, JSON) in json {
//Do something you want
}
SwiftyJSON 讓我們更好更簡單的處理JSON編碼,總之,簡單實用,值得推薦。
備注參考
https://github.com/SwiftyJSON/SwiftyJSON
http://tangplin.github.io/swiftyjson/