說明:
json可以拆解成Array,以[]表示,例:[{"id": "#123", "name": "Apple"},{"id": "#321", "name": "Google"}]。
另一種是Object,以{"key": "value"}表示,如http://date.jsontest.com/提供的:
{
"time": "03:53:25 AM",
"milliseconds_since_epoch": 1362196405309,
"date": "03-02-2013"
}
這兩種格式可分別使用Swift內建NSArray跟NSDictionary來Parse,那Array內又有Array該如何Parse呢?
做法:
假設有一json如下:
{
"Parents": [ {"id": "#123",
"name": "Daddy1",
"Children": [ {"c_id": "#124",
"c_name": "kid1"},
{"c_id": "#125",
"c_name": "kid2"}]
},
{"id": "#234",
"name": "Daddy2",
"Children": [ {"c_id": "#235",
"c_name": "kid1"},
{"c_id": "#236",
"c_name": "kid2"}]
},
{"id": "#345",
"name": "Daddy3",
"Children": [ {"c_id": "#346",
"c_name": "kid1"},
{"c_id": "#347",
"c_name": "kid2"}]
}
]
}
var arrResult = json.objectForKey("Parents") as NSArray;
var row: NSDictionary;
var rowSub: NSDictionary;
var arrSubResult : NSArray;
var strID: String;
var strName: String;
var strC_ID: String;
var strC_Name: String;
var arrTotalResult = [DataModel]();
for var i=0 ; i < arrResult.count ; i++ {
row = arrResult[i] as NSDictionary;
arrSubResult = row.objectForKey("Children") as NSArray;
strID = row["ID"] as String;
strName = row["NAME"] as String;
for var j=0 ; j < arrSubResult.count ; j++ {
rowSub = arrSubResult[j] as NSDictionary;
strC_ID = row["C_ID"] as String;
strC_Name = row["C_NAME"] as String;
//使用data model
let data = DataModel(ID: self.strID, Name: self.strName, C_ID: self.strC_ID, C_Name: self.C_Name);
arrTotalResult.append(data);
}
}
沒有留言:
張貼留言