0%

[swift] NetWork (4) 解析Json

  • 先做一個json檔案來模擬接到時怎麼解析 ```csharp
    {
    “組織名稱”:”普攏拱團隊”,
    “組織成員”:[
    {“姓名”:”科科人”,”年齡”:11},
    {“姓名”:”可可狗”,”年齡”:120}
    ]
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

* 在viewDidLoad加上,測試看看!! ```swift
//將檔案讀出來
let path = NSBundle.mainBundle().pathForResource("json", ofType: "txt");
var data:NSData = NSData(contentsOfFile: path!)!;
//解析Json
var jsonobj = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary;
println(jsonobj["組織名稱"] as String);
println("組織成員");
var arr = jsonobj["組織成員"] as NSArray;
for i in (0...arr.count - 1){
let mdic = arr[i] as NSDictionary;
println(mdic["姓名"] as String);
println(mdic["年齡"] as Int);
}