SwiftyJSON的使用詳解


https://blog.csdn.net/ly410726/article/details/80235007

 

 

1,SwiftyJSON介紹與配置
SwiftyJSON是個使用Swift語言編寫的開源庫,可以讓我們很方便地處理JSON數據(解析數據、生成數據)。
GitHub地址: https://github.com/SwiftyJSON/SwiftyJSON
使用配置:直接將 SwiftyJSON.swift 添加到項目中即可。
 
2,SwiftyJSON的優點
同 JSONSerializationSwiftyJSON 相比,在獲取多層次結構的JSON數據時。SwiftyJSON不需要一直判斷這個節點是否存在,是不是我們想要的class,下一個節點是否存在,是不是我們想要的class…。同時,SwiftyJSON內部會自動對optional(可選類型)進行拆包(Wrapping ),大大簡化了代碼。
下面通過幾個樣例作為演示。(本文代碼均已升級至 Swift3)
 
(1)比如我們有一個如下的JSON數據,表示聯系人集合:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[
     {
         "name" "hangge"
         "age" : 100, 
         "phones" : [
             {
                 "name" "公司"
                 "number" "123456"
             }, 
             {
                 "name" "家庭"
                 "number" "001"
             }
         ]
     },
     {
         "name" "big boss"
         "age" : 1, 
         "phones" : [
             {
                 "name" "公司"
                 "number" "111111"
             }
         ]
     }
]
為便於測試比較,我們先將JSON格式的字符串轉為Data:
1
2
3
4
5
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.data(using:  String . Encoding .utf8, allowLossyConversion:  false ) {
     //.........
}

(2)使用JSONSerializationSwiftyJSON解析
比如我們要取第一條聯系人的第一個電話號碼,每個級別都判斷就很麻煩,代碼如下:
1
2
3
4
5
6
7
if  let  userArray = try?  JSONSerialization .jsonObject(with: jsonData,
                                         options: .allowFragments)  as ? [[ String AnyObject ]],
     let  phones = userArray?[0][ "phones" as ? [[ String AnyObject ]],
     let  number = phones[0][ "number" as String  {
     // 找到電話號碼
     print ( "第一個聯系人的第一個電話號碼:" ,number)
}
即使使用optional來簡化一下,代碼也不少:
1
2
3
4
5
6
if  let  userArray = try?  JSONSerialization .jsonObject(with: jsonData,
                                         options: .allowFragments)  as ? [[ String AnyObject ]],
     let  number = (userArray?[0][ "phones" as ? [[ String AnyObject ]])?[0][ "number" as String  {
     // 找到電話號碼
     print ( "第一個聯系人的第一個電話號碼:" ,number)
}

(3)使用SwiftyJSON解析:
不用擔心數組越界,不用判斷節點,拆包什么的,代碼如下:
1
2
3
4
5
let  json =  JSON (data: jsonData)
if  let  number = json[0][ "phones" ][0][ "number" ].string {
     // 找到電話號碼
     print ( "第一個聯系人的第一個電話號碼:" ,number)
}
原文:Swift - SwiftyJSON的使用詳解(附樣例,用於JSON數據處理)
如果沒取到值,還可以走到錯誤處理來了,打印一下看看錯在哪:
1
2
3
4
5
6
7
8
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)與URLSession結合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//創建URL對象
let  url =  URL (string: "http://www.hangge.com/getJsonData.php" )
//創建請求對象
let  request =  URLRequest (url: url!)
 
let  dataTask =  URLSession .shared.dataTask(with: request,
                        completionHandler: {(data, response, error) ->  Void  in
                         if  error !=  nil {
                             print (error)
                         } else {
                             let  json =  JSON (data: data!)
                             if  let  number = json[0][ "phones" ][0][ "number" ].string {
                                 // 找到電話號碼
                                 print ( "第一個聯系人的第一個電話號碼:" ,number)
                             }
                         }
})  as  URLSessionTask
 
//使用resume方法啟動任務
dataTask.resume()

(2)與Alamofire結合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//創建URL對象
let  url =  URL (string: "http://www.hangge.com/getJsonData.php" )!
 
Alamofire .request(url).validate().responseJSON { response  in
     switch  response.result.isSuccess {
     case  true :
         if  let  value = response.result.value {
             let  json =  JSON (value)
             if  let  number = json[0][ "phones" ][0][ "number" ].string {
                 // 找到電話號碼
                 print ( "第一個聯系人的第一個電話號碼:" ,number)
             }
         }
     case  false :
         print (response.result.error)
     }
}
 
4,獲取值 
(1)可選值獲取(Optional getter)
通過.number、.string、.bool、.int、.uInt、.float、.double、.array、.dictionary、int8、Uint8、int16、Uint16、int32、Uint32、int64、Uint64等方法獲取到的是可選擇值,我們需要自行判斷是否存在,同時不存在的話可以獲取具體的錯誤信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//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 這樣的屬性獲取值,如果沒獲取到的話會返回一個默認值。省得我們再判斷拆包了。
1
2
3
4
5
6
7
8
9
10
11
//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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
let  jsonObject = json.object  as  AnyObject
 
let  jsonObject = json.rawValue   as  AnyObject
 
//JSON轉化為Data
let  data = json.rawData()
 
//JSON轉化為String字符串
if  let  string = json.rawString() {
     //Do something you want
}
 
//JSON轉化為Dictionary字典([String: AnyObject]?)
if  let  dic = json.dictionaryObject {
     //Do something you want
}
 
//JSON轉化為Array數組([AnyObject]?)
if  let  arr = json.arrayObject {
     //Do something you want
}

5,設置值
1
2
3
4
json[0][ "age" ].int =  101
json[0][ "name" ].string =   "hangge.com"
json[0][ "phones" ].arrayObject = [[ "name" : "固話" "number" :110],[ "name" : "手機" "number" :120]]
json[0][ "phones" ][0].dictionaryObject = [ "name" : "固話" "number" :100]

6,下標訪問(Subscript)
可以通過數字、字符串、數組類型的下標訪問JSON數據的層級與屬性。比如下面三種方式的結果都是一樣的:
1
2
3
4
5
6
7
8
9
//方式1
let  number = json[0][ "phones" ][0][ "number" ].stringValue
     
//方式2
let  number = json[0, "phones" ,0, "number" ].stringValue
     
//方式3
let  keys:[ JSONSubscriptType ] = [0, "phones" ,0, "number" ]
let  number = json[keys].stringValue
 
7,循環遍歷JSON對象中的所有數據
(1)如果JSON數據是數組類型(Array)
1
2
3
for  (index,subJson):( String JSON in  json {
     print ( "\(index):\(subJson)" )
}
原文:Swift - SwiftyJSON的使用詳解(附樣例,用於JSON數據處理)
 
(2)如果JSON數據是字典類型(Dictionary)
1
2
3
for  (key,subJson):( String JSON in  json[0] {
     print ( "\(key):\(subJson)" )
}
原文:Swift - SwiftyJSON的使用詳解(附樣例,用於JSON數據處理)
 
8,構造創建JSON對象數據
(1)空的JSON對象
1
let  json:  JSON  =   nil

(2)使用簡單的數據類型創建JSON對象
1
2
3
4
5
6
7
8
9
10
11
//StringLiteralConvertible
let  json:  JSON  "I'm a son"
 
//IntegerLiteralConvertible
let  json:  JSON  =  12345
 
//BooleanLiteralConvertible
let  json:  JSON  =   true
 
//FloatLiteralConvertible
let  json:  JSON  =  2.8765

(3)使用數組或字典數據創建JSON對象
1
2
3
4
5
6
7
8
9
10
11
12
//DictionaryLiteralConvertible
let  json:  JSON  =  [ "I" : "am" "a" : "son" ]
 
//ArrayLiteralConvertible
let  json:  JSON  =  [ "I" "am" "a" "son" ]
 
//Array & Dictionary
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:[ JSONSubscriptType ] = [ "list" ,3, "what" ]
json[path] =  "that"


原文出自:www.hangge.com  轉載請保留原文鏈接:http://www.hangge.com/blog/cache/detail_968.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM