我不太清楚如何你的映射這一任務的對象,但我通過與JSON字符串解析NSData
:
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
在這種情況下,我得到一個NSDictionary
一個關鍵,「產品」 ,該鍵的對象是另一個字典。 NSDictionary
與「任務」鍵的對象是四個NSDictionary
對象的NSArray
。
現在,該JSON摘錄是無效的JSON,但我認爲它只是一個更廣泛的JSON文件的葉。但是出於測試目的,我們假設JSON文件如下:
{
"product" : {
"id": 123,
"name": "Produce RestKit Sample Code",
"description": "We need more sample code!",
"tasks": [
{"name": "Identify samples to write", "assigned_user_id": 1},
{"name": "Write the code", "assigned_user_id": 1},
{"name": "Push to Github", "assigned_user_id": 1},
{"name": "Update the mailing list", "assigned_user_id": 1}]
}
}
然後我就可以解析JSON像這樣:
NSString *filename = [[NSBundle mainBundle] pathForResource:@"13628140" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:filename];
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
NSDictionary *product = dictionary[@"product"];
NSArray *tasks = product[@"tasks"];
NSDictionary *firstTask = tasks[0];
NSString *firstName = firstTask[@"name"];
NSString *firstAssignedUserId = firstTask[@"assigned_user_id"];
,或者,如果你想通過任務一一列舉:
NSDictionary *product = dictionary[@"product"];
NSArray *tasks = product[@"tasks"];
[tasks enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSDictionary *task = obj;
NSLog(@"Task \"%@\" is assigned to %@", task[@"name"], task[@"assigned_user_id"]);
}];
你只是問如何存儲tasks
的是NSArray
在覈心數據?
來源
2012-11-29 14:51:11
Rob
感謝您的回答。實際上,我設法解析「任務」,但問題是將它們放入Coredata中而不創建重複的任務。 現在我攔截對象加載器的「willMapData」委託並在添加新對象之前刪除解析的「產品」的所有「任務」。它可以工作,但並不像我希望的那樣乾淨。 – Vassily