SwiftyJSON 可以讓你在 Swift 語言中更好的處理 JSON 數據
1,SwiftyJSON介紹與配置
SwiftyJSON是個使用Swift語言編寫的開源庫,可以讓我們很方便地處理JSON數據(解析數據、生成數據)。 GitHub地址:https://github.com/SwiftyJSON/SwiftyJSON
使用配置:直接 SwiftyJSON.swift 添加到項目中即可。
2,SwiftyJSON的優點
同 NSJSONSerializationSwiftyJSON 相比,在獲取多層次結構的JSON數據時。SwiftyJSON不需要一直判斷這個節點是否存在,是不是我們想要的class,下一個節點是否存在,是不是我們想要的class…。同時,SwiftyJSON內部會自動對optional(可選類型)進行拆包(Wrapping ),大大簡化了代碼。 (1)比如我們有一個如下的JSON數據,表示聯系人集合:
[{
"name" :
"hangge" ,
"age" :
100 ,
"phones" : [{
"name" :
"公司" ,
"number" :
"123456" },{
"name" :
"家庭" ,
"number" :
"001" }]},{
"name" :
"big boss" ,
"age" :
1 ,
"phones" : [{
"name" :
"公司" ,
"number" :
"111111" }]}
]
為便于測試比較,我們先將JSON格式的字符串轉為NSData:let jsonStr =
"[{\" name\
": \" hangge\
", \" age\
": 100, \" phones\
": [{\" name\
": \" 公司\
",\" number\
": \" 123456 \
"}, {\" name\
": \" 家庭\
",\" number\
": \" 001 \
"}]}, {\" name\
": \" big boss\
",\" age\
": 1,\" phones\
": [{ \" name\
": \" 公司\
",\" number\
": \" 111111 \
"}]}]" if let jsonData = jsonStr.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false ) {//.........
}
(2)使用NSJSONSerializationSwiftyJSON解析 比如我們要取第一條聯系人的第一個電話號碼,每個級別都判斷就很麻煩,代碼如下:
if let userArray = try? NSJSONSerialization.JSONObjectWithData(jsonData,options: .AllowFragments) as?
[[String: AnyObject]] ,let phones = userArray?[
0 ][
"phones" ] as?
[[String: AnyObject]] ,let number = phones[
0 ][
"number" ] as? String {// 找到電話號碼
print (
"第一個聯系人的第一個電話號碼:" ,number)
}
即使使用optional來簡化一下,代碼也不少:
if let userArray = try? NSJSONSerialization.JSONObjectWithData(jsonData,options: .AllowFragments) as?
[[String: AnyObject]] ,let number = (userArray?[
0 ][
"phones" ] as?
[[String: AnyObject]] )?[
0 ][
"number" ]as? String {// 找到電話號碼
print (
"第一個聯系人的第一個電話號碼:" ,number)
}
(3)使用SwiftyJSON解析: 不用擔心數組越界,不用判斷節點,拆包什么的,代碼如下:
let json = JSON(data: jsonData)
if let number = json[
0 ][
"phones" ][
0 ][
"number" ].string {
// 找到電話號碼
print("第一個聯系人的第一個電話號碼:",number)
}
原文:Swift - SwiftyJSON的使用祥解(附樣例,用于JSON數據處理)
如果沒取到值,還可以走到錯誤處理來了,打印一下看看錯在哪:let json = JSON(data: jsonData)
if let number = json[
0 ][
"phones" ][
0 ][
"number" ].string {
// 找到電話號碼
print("第一個聯系人的第一個電話號碼:",number)
}else {
// 打印錯誤信息
print(json[0]["phones"][0]["number"])
}
3,獲取網絡數據,并使用SwiftyJSON解析 除了解析本地的JSON數據,我們其實更常通過url地址獲取遠程數據并解析。
(
1 )與NSURLSession結合
let urlString:String=
"http://www.111cn.net /getJsonData.php"
let url:NSURL! = NSURL(
string :urlString)
let request:NSURLRequest = NSURLRequest(URL: url)
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request,completionHandler: {(data, response, error) -> Void
in if error != nil{print(error?.code)print(error?.description)}
else {
let json = JSON(data: data!)
if let number = json[
0 ][
"phones" ][
0 ][
"number" ].
string {print(
"第一個聯系人的第一個電話號碼:" ,number)}}
})
as NSURLSessionTask
dataTask.resume()
(
2 )與Alamofire結合
let urlString:String=
"http://www.111cn.net /code/test.php"
let url:NSURL! = NSURL(
string :urlString)Alamofire.request(.GET, url).validate().responseJSON { response
in switch response.result {
case .Success:
if let value = response.result.
value {
let json = JSON(
value )
if let number = json[
0 ][
"phones" ][
0 ][
"number" ].
string {print(
"第一個聯系人的第一個電話號碼:" ,number)}}
case .Failure(
let error):print(error)}
}
4,獲取值 (1)可選值獲取(Optional getter) 通過.number、.string、.bool、.int、.uInt、.float、.double、.array、.dictionary、int8、Uint8、int16、Uint16、int32、Uint32、int64、Uint64等方法獲取到的是可選擇值,我們需要自行判斷是否存在,同時不存在的話可以獲取具體的錯誤信息。
//int
if let age = json[
0 ][
"age" ].int {
print(age)
} else {
//打印錯誤信息
print(json[0]["age"])
}//String
if let name = json[
0 ][
"name" ].string {
print(name)
} else {
//打印錯誤信息
print(json[0]["name"])
}
(2)不可選值獲取(Non-optional getter) 使用 xxxValue 這樣的屬性獲取值,如果沒獲取到的話會返回一個默認值。省得我們再判斷拆包了。
//If not a Number or nil, return 0
let age: Int = json[
0 ][
"age" ].intValue//If not a String or nil, return ""
let name: String = json[
0 ][
"name" ].stringValue//If not a Array or nil, return []
let list: Array
<JSON > = json[
0 ][
"phones" ].arrayValue//If not a Dictionary or nil, return [:]
let phone: Dictionary
<String, JSON > = json[
0 ][
"phones" ][
0 ].dictionaryValue
(3)獲取原始數據(Raw object)
let jsonObject: AnyObject = json.
object if let jsonObject: AnyObject = json.rawValue
if let data = json.rawData() {
}
if let string = json.rawString() {
}
5,設置值
json[
0 ][
"age" ].int = 101
json[
0 ][
"name" ].string = "111cn.net "
json[
0 ][
"phones" ].arrayObject = [["name":"固話", "number":110],["name":"手機", "number":120]]
json[
0 ][
"phones" ][
0 ].dictionaryObject = ["name":"固話", "number":100]
6,下標訪問(Subscript) 可以通過數字、字符串、數組類型的下標訪問JSON數據的層級與屬性。比如下面三種方式的結果都是一樣的:
let number = json[
0 ][
"phones" ][
0 ][
"number" ].stringValue
let number = json[
0 ,
"phones" ,
0 ,
"number" ].stringValue
let keys:[JSONSubscriptType] = [
0 ,
"phones" ,
0 ,
"number" ]
let number = json[keys].stringValue
7,循環遍歷JSON對象中的所有數據
(1)如果JSON數據是數組類型(Array)
for (index,subJson):(
String ,
JSON )
in json {print(
"\(index):\(subJson)" )
}
(2)如果JSON數據是字典類型(Dictionary)
for (key,subJson):(
String ,
JSON )
in json[
0 ] {print(
"\(key):\(subJson)" )
}
8,構造創建JSON對象數據 (1)空的JSON對象
let json:
JSON = nil
(2)使用簡單的數據類型創建JSON對象
let json:
JSON =
"I'm a son"
let json:
JSON =
12345
let json:
JSON =
true
let json:
JSON =
2.8765
(3)使用數組或字典數據創建JSON對象
let json:
JSON = [
"I" :
"am" ,
"a" :
"son" ]
let json:
JSON = [
"I" ,
"am" ,
"a" ,
"son" ]
var json:
JSON = [
"name" :
"Jack" ,
"age" :
25 ,
"list" : [
"a" ,
"b" ,
"c" , [
"what" :
"this" ]]]
json[
"list" ][
3 ][
"what" ] =
"that"
json[
"list" ,
3 ,
"what" ] =
"that"
let path = [
"list" ,
3 ,
"what" ]
json[path] =
"that"
總結
以上是生活随笔 為你收集整理的数据存储之SwiftJSON 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。